var guestId = 0;
var ownerId = 0;
var roomtypeId = 0;
var roomName = 0;
var roomId = 0;
var roomStatusId = 0;
var TabsData = [];
//Tabs Management
function getTabsData(resId)
{
	for(var i=0;i<TabsData.length;i++)
	{
		if(TabsData[i].resId == resId)
			return TabsData[i];
		else if(TabsData[i].viewResIdInGroup!=null && getObjectFromDataIndex(TabsData[i].GroupResvList,"resId",resId))
			return getObjectFromDataIndex(TabsData[i].GroupResvList,"resId",TabsData[i].viewResIdInGroup);
	}
	return null;
}
function getCurrentTab(){return $("[id*=tappage_roommanage_menu_].select")}
function getCurrentTabData()
{
	var resId = getCurrentTab().attr('refid');
	var current = getTabsData(resId);
	
	if(current!=null && current.viewResIdInGroup != null)
	{
		var singleInGroup = getObjectFromDataIndex(current.GroupResvList,"resId",current.viewResIdInGroup);
		if(singleInGroup != null) singleInGroup.getParentGroup = function(){ return current; };
		return singleInGroup;
	}
	return current;
}
function getCurrentTabPayment(){
	var Tabs = getCurrentTabData();
	if(Tabs == null) return null;
	return Tabs.Payment;
}

function CallEditReservedPageWithLoadElement(e,id){
	if($("div[forload=editreserved] [name=editReserved_group]").size() == 0){
		waitingDialog({});
		document.callEditReservedPageE = e;
		document.callEditReservedPageId = id;
		var div = $("<div>");
		$("div[forload=editreserved]").append(div);
		div.load("/components/EditReserved/EditReserved.jsp",function(){
			var e = document.callEditReservedPageE;
			var id = document.callEditReservedPageId;
			delete document.callEditReservedPageE;
			delete document.callEditReservedPageId;
			CallEditReseredPage(e,id);
		});
	}
	else{CallEditReseredPage(e,id)}
}

//Prepare TabData
function CallEditReseredPage(e,id){
	var roomTypeString = $("#rmt").attr("roomtype");
	var roomString =$("[name*=roomOnPopup]").val();
	if($("#BookingDetailsS").is(":visible")) $("#BookingDetailsS").dialog("destroy");
	if($("#BookingDetailsG").is(":visible")) $("#BookingDetailsG").dialog("destroy");
	if($("#BookingG").is(":visible")) { $("#BookingG").dialog("destroy"); ClearSpanSelection(); }
	var Tabs = getTabsData(id);
	if(Tabs != null)
	{
		if(id == 0) Tabs.type = (e=="btnEditS")? "Single": "Group";
		DisplayframeReserved("editreserved" + Tabs.resId);
		return;
	}
	else Tabs = {};
		TabsData.push(Tabs);
		if(e!="pamentPageS"&&e!="pamentPageG"){
			Tabs.type = (e=="btnEditS")? "Single": "Group";
			Tabs.resId = id;
			Tabs.page = "Detail";
		}else
		{
			Tabs.type = (e=="pamentPageS")? "Single": "Group";
			Tabs.resId = id;
			Tabs.page = "Payment";
		}
	if(Tabs.ResData == null,Tabs.resId==0)
	{
		Tabs.ResData={};
		Tabs.Owner={};
		Tabs.Agency={};
		if(Tabs.type == "Single")
			Tabs.ResData.roomTypeString = roomTypeString;
		else
			Tabs.ResData.roomtypeString = roomTypeString;
		
		Tabs.Owner.firstName = $('#name3').val();
		Tabs.Owner.lastName =$('#lastname3').val();
		Tabs.Owner.phone =$('#tel3').val();
		Tabs.Owner.mail=$('#email3').val();
		Tabs.Agency.agency="";
		
		Tabs.ResData.id=0;
		Tabs.ResData.span =daysBetween($.datepicker.parseDate("yy-mm-dd",$(dateStart).attr('dateform')).getTime(),$.datepicker.parseDate("yy-mm-dd",$(dateEnd).attr('dateend')).getTime());
		Tabs.ResData.roomString =roomString; 
		Tabs.ResData.adult = $('#adult3').val();
		Tabs.ResData.child = $('#child3').val();
		Tabs.ResData.salutation =$('#salutation3').val();
		Tabs.ResData.guestName = $('#name3').val();
		Tabs.ResData.guestLastName = $('#lastname3').val();
		Tabs.ResData.guestTel = $('#tel3').val();
		Tabs.ResData.email = $('#email3').val();
		Tabs.ResData.isAssign =$("[name=\"isAssign\"]").is(":checked");
		Tabs.ResData.agencyName =$('#nameAgent3').val();
		Tabs.ResData.date=$.datepicker.parseDate("yy-mm-dd",$(dateStart).attr('dateform')).toString();
		Tabs.ResData.agency="";
		if ($('#pledge').val() == null || $('#pledge').value == "")
			Tabs.ResData.pay = 0;
		else
			Tabs.ResData.pay = $('#pledge').val();
		Tabs.ResData.order = $('#roomAmount3').val();
		if ($('#SeasonalRate').val() != "1") 
			Tabs.ResData.priceRateString = $('#SeasonalRate').val();
		else
			Tabs.ResData.priceRateString = $('#SeasonalRate3').val();

		CreateChargeforEmptyRoom($('#dep').text(),Tabs);
		CreatePaymentForEmptyRoom(Tabs);
	}
	
	waitingDialog({});
	var services = [];
	if(SharedData.Salutation==null)services.push(["/popupService",{doClass:"loadSalutation"},function(e){SharedData.Salutation=JSON.parse(e)},null]);
	if(SharedData.RoomTax==null)services.push(["/taxService",{func:"getRoomTax"},function(e){SharedData.RoomTax=JSON.parse(e)},null]);
	if(SharedData.Package==null)services.push(["/popupService",{doClass : "loadPackage"},function(e){SharedData.Package=JSON.parse(e)},null]);
	if(SharedData.SourcesBusiness==null)services.push(["/sourcesbusinessService",{func: "selectSourceBuss"},function(e){SharedData.SourcesBusiness=JSON.parse(e)},null]);
	if(SharedData.ArrivalMode==null)services.push(["/modearrivalService",{func: "loadAllModeArrival"},function(e){SharedData.ArrivalMode=JSON.parse(e)},null]);
	if(Tabs.resId != 0){
		if(Tabs.type == "Single"){
			loadResSingle(Tabs.resId,"0",services);
		}else if(Tabs.type == "Group"){
			loadResGroup(Tabs.resId,Tabs,services);
		}
	}
	else{
		if(services.length!=0)
		arrayservice(services,function(){
			closeWaitingDialog();
			CreateNewTapPage(Tabs);
			DisplayDetail();
		});
	}
}

function loadResData(resId,groupId)
{
	if(groupId != "0")
		loadResGroup(groupId);
	else
		loadResSingle(resId);
}

function loadResSingle(resId,data,services){
	if(services==null) services = [];
	services.splice(0,0,["/reservationService",{ func : "getReservation", resId: resId },function(data){
		var objArray = JSON.parse(data);
		var Tabs = getTabsData(objArray.id);
		Tabs.ResData = objArray;
		loadOwner(Tabs);
	},null]);
	arrayservice(services,function(){});
}

function loadResGroup(groupId,Tabs,services)
{
	if(services==null) services = [];
	var Tabs = getTabsData(groupId);
	services.push(["/reservationService",{ func : "loadGroup", groupId: groupId },function(data,args) { var objArray = JSON.parse(data);var Tabs = getTabsData(objArray.id);Tabs.ResData = objArray; },null]);
	services.push(["/reservationService",{ func : "loadGroupResvList", groupId: groupId },load_groupResvList_success,Tabs]);
	arrayservice(services,function(Tabs){loadOwner(Tabs);},Tabs);
}
function load_groupResvList_success(data,Tabs){
	var objArray = JSON.parse(data);
	Tabs.GroupResvList = [];
	for(var i=0;i<objArray.length;i++)
	{
		var tmp = {
			page: "Detail",
			type: "Single",
			resId: objArray[i].id,
			fromGroupId: Tabs.resId,
			Task: objArray[i].Task
		};
		tmp.ResData = objArray[i];
		Tabs.GroupResvList.push(tmp);
	}
}
function loadOwner(Tabs){
	if(Tabs.fromGroupId != null &&  Tabs.ResData.guestString == "0")
		CallDetailLoad(Tabs);
	else
	{
		var url = "/popupService";
		var data = { doClass : "loadGuest", guestId: Tabs.ResData.guestString };
		simpleserviceWithArgs(url,data,function(data,Tabs){
			Tabs.Owner = JSON.parse(data);
			(Tabs.fromGroupId == null)?CreateNewTapPage(Tabs):"";
			CallDetailLoad(Tabs);
		},Tabs);
	}
}
function CreateNewTapPage(Tabs){
	$(".select").attr("class","showdisplay");
	var str = "<div  id=\"tappage_roommanage_menu_editreserved{0}\" guestIdER=\"{1}\" groupIdER=\"{2}\" resIdER=\"{3}\" refId=\"{4}\" onclick=\"DisplayframeReserved(title)\"class=\"select\" title=\"editreserved{5}\"><div id=\"editres_status_color\" style=\"width:8px; height:8px; background-color:#FFF; float:left; margin-top:4px;\" >&nbsp;</div>&nbsp;&nbsp;{6}&nbsp;&nbsp;</div><img src=\"../../images/components/tappage/cancel.png\" width=\"13px\" height=\"13px\" title=\"editreserved{7}\"  onclick=\"CloseTapPage(title)\" class =\"closebutton\">";
	var name = addguest_label;
	var guestString = "-";
	if(Tabs.Owner != null)
		name = Tabs.Owner.firstName + " " + Tabs.Owner.lastName;
	
	if(Tabs.type=="Group")
	{
		$("#tabs").append(str.format(
			Tabs.resId,
			(Tabs.ResData == null)? "-": Tabs.ResData.guestString,
			Tabs.resId,
			"",
			Tabs.resId,
			Tabs.resId,
			name + " (G)",
			Tabs.resId
		));
	}
	else if(Tabs.type=="Single")
	{
		$("#tabs").append(str.format(
			Tabs.resId,
			(Tabs.ResData == null)? "-": Tabs.ResData.guestString,
			"",
			Tabs.resId,
			Tabs.resId,
			Tabs.resId,
			name,
			Tabs.resId
		));
	}
}
function CallDetailLoad(Tabs){
	
	if(Tabs.type == "Single")
		task_data = {func:"GetTaskNoteList",task_id:Tabs.ResData.taskListString};
	else
		task_data = {func:"GetTaskNoteList",task_id:Tabs.ResData.taskListString};
	var CreditCard_service=["/popupService",{ doClass : "loadCreditCard", guestId: Tabs.ResData.guestString },load_creditcard_success,Tabs];
	var agency_service = ["/agencyService", {func:"loadagency", agencyId: Tabs.ResData.agencyIdString},load_agency_success,Tabs];
	var task_service = ["/taskService",task_data,load_taskGroup_success,Tabs];
	var split_table = ["/subReservationService", { func : "GetAllRoomInReservation", resId: Tabs.resId},load_split_table_success,Tabs];
	var loadGuest_service =["/reservationService",{func : "loadGuestList" , resId:Tabs.resId},loadGuest_success,Tabs];
	var load_Grouptravel_service=["/TravelService",{func:"loadtravelG" , groupId:Tabs.resId},load_grouptravel_success,Tabs];
	var load_Singletravel_service=["/TravelService",{func:"loadtravelN" , resId:Tabs.resId},load_restravel_success,Tabs];
	var load_PackageBydate_service=["/packageService",{doClass:"getPackageByDate",packageId:Tabs.ResData.priceRateString},load_PackageBydate_success,Tabs];
	var load_roomcharge_service=["/chargeService?",{func:"getCharge",chargeId:Tabs.ResData.chargeListString},load_roomcharge_success,Tabs];
	var services = [agency_service];
	if(Tabs.ResData.guestString!=null&&Tabs.ResData.guestString!=0)
		services.push(CreditCard_service);
	if(Tabs.ResData.taskListString != ""&&Tabs.ResData.taskListString!=undefined)
		services.push(task_service);
	if(Tabs.type == "Group")
	{
		services.push(load_Grouptravel_service);
		services.push(["/paymentService?",{func:"getPayment",paymentId:Tabs.ResData.paymentListString},load_Group_payment_success,Tabs]);
		services.push(["/chargeService?",{func:"getCharge",chargeId:Tabs.ResData.OtherChargeString},load_Group_charge_success,Tabs]);
		var rooms = Tabs.GroupResvList;
		for(var i=0;i<rooms.length;i++)
		{
			if(rooms[i].ResData.otherChargeListString == null)
				chargeData= rooms[i].ResData.chargeListString;
			else
				chargeData= rooms[i].ResData.chargeListString+","+rooms[i].ResData.otherChargeListString;
			services.push(["/paymentService?",{func:"getPayment",paymentId:rooms[i].ResData.paymentListString},LoadResInGroupPaymentSuccess,rooms[i].resId]);
			services.push(["/chargeService?",{func:"getCharge",chargeId:chargeData},LoadResInGroupChargeSuccess,rooms[i].resId]);
			services.push(["/reservationService",{func : "loadGuestList" ,resId:rooms[i].resId},LoadResInGroupGuestSuccess,rooms[i].resId]);
			services.push(["/folioService?",{func:"loadSingleFolioList",resId:rooms[i].resId},loadResInGroupfoliosuccess,rooms[i].resId]);
			
		}	
	}
	else
	{
		services.splice(0,0,load_roomcharge_service);
		services.push(load_Singletravel_service);
		if(Tabs.Owner != null) services.push(loadGuest_service);
		services.push(split_table);
		services.push(load_PackageBydate_service);
		if(Tabs.ResData.paymentListString!=null&&Tabs.ResData.paymentListString!="")services.push(["/paymentService?",{func:"getPayment",paymentId:Tabs.ResData.paymentListString},load_payment_success,Tabs]);
		if(Tabs.ResData.otherChargeListString!=null&&Tabs.ResData.otherChargeListString!="")services.push(["/chargeService?",{func:"getCharge",chargeId:Tabs.ResData.otherChargeListString},load_othercharge_success,Tabs]);
	}
		arrayservice(services,DisplayDetail,Tabs);
}
function load_creditcard_success(data,Tabs){Tabs.CreditCard =JSON.parse(data);}
function load_agency_success(data,Tabs){ Tabs.Agency = JSON.parse(data); }
function load_taskGroup_success(data,Tabs){ Tabs.Task = JSON.parse(data); }
function loadGuest_success(data,Tabs){Tabs.guest = JSON.parse(data); }
function load_grouptravel_success(data,Tabs) { Tabs.GroupTravel = JSON.parse(data);	 }
function load_restravel_success(data,Tabs) { Tabs.SingleTravel = JSON.parse(data);	 }
function load_PackageBydate_success(data,Tabs) { Tabs.PacByDate = JSON.parse(data);	}
function load_payment_success(data,Tabs){Tabs.PaymentList = JSON.parse(data);}
function load_othercharge_success(data,Tabs){Tabs.OtherChargeList = JSON.parse(data);}
function load_roomcharge_success(data,Tabs){Tabs.ChargeList=JSON.parse(data)}
function load_Group_payment_success(data,Tabs){Tabs.GroupPaymentList=JSON.parse(data)}
function load_Group_charge_success(data,Tabs){Tabs.ChargeList=JSON.parse(data)}
function LoadResInGroupPaymentSuccess(data,resId)
{
	var Tabs = getCurrentTabData();
	var rooms = Tabs.GroupResvList;
	for(var i=0;i<rooms.length;i++)
		if(rooms[i].resId == resId){
			rooms[i].PaymentList=JSON.parse(data); break;
		}
}
function LoadResInGroupChargeSuccess(data,resId)
{
	var Tabs = getCurrentTabData();
	var rooms = Tabs.GroupResvList;
	for(var i=0;i<rooms.length;i++)
		if(rooms[i].resId == resId){
			rooms[i].ChargeList=JSON.parse(data); break;
		}
}
function LoadResInGroupGuestSuccess(data,resId)
{ 
	var Tabs = getCurrentTabData();
	var rooms = Tabs.GroupResvList;
	for(var i=0;i<rooms.length;i++)
		if(rooms[i].resId == resId){
			rooms[i].guest=JSON.parse(data); break;
		}
}
function loadResInGroupfoliosuccess(data,resId)
{
	var Tabs = getCurrentTabData();
	var rooms = Tabs.GroupResvList;
	for(var i=0;i<rooms.length;i++)
		if(rooms[i].resId == resId){
			rooms[i].FolioList=JSON.parse(data); break;
		}
}
//Render Data
function HideAllPage(){
	$("[for=front]").css("display","none");
	$("[name=edit_groups]").css("display","none");
	$("[name=edit_none_groups]").css("display","none");
	$("#payment-dialog").css("display","none");
	$("#single-payment-dialog").css("display","none");
	$("#single-payment-info").css("display","none");
	$("[id*=tappage_newpage_]").remove();
	$("[name=SavedetailG]").css("display","none");
}
function DisplayDetail(){
	var Tabs = getCurrentTabData();
	if(Tabs == null) return;
	HideAllPage();
	if(Tabs.type == "Manage"){
		waitingDialog();
		RenderRoomManagementPage(Tabs);
	}else if(Tabs.page == "Detail"){
		if(Tabs.type == "Group")
			$("[name=edit_groups]").css("display","");
		else
			$("[name=edit_none_groups]").css("display","");
		fillOwnerInfo(Tabs);
		fillOwner(Tabs); 
		fillReservationDetailcantEdit();
		fillcreditCardcantEdit();
		fillTravelcantEdit();
		renderReservationTableDetailPage(Tabs);
		if(Tabs.type == "Group"){
			displayGroupTask(Tabs);
			showResvList(Tabs);
			fillRoomDetailandGuestAmount();
			GroupCalBalancetoShow();
		}else{
			//CalExtrabed();
			displaySingleTask(Tabs);
			fillPackageTable();
			LoadGuest(Tabs);
		}
		if(Tabs.resId == 0)
		{
			if(Tabs.type == "Group")
			{
				
				$("[id*=edit_res_resdetails_checkin]").val(new Date($(dateStart).attr("dateform")).getFormatedString())
				$("[id*=edit_res_resdetails_checkout]").val(new Date($(dateEnd).attr("dateend")).getFormatedString());
				$("#resvList").find("tr:last").hide();
				var roomAmount =parseInt(Tabs.ResData.order);
				for(var n=0;n<roomAmount;n++)
					AddReservation($('<input type="button" class="active"name="insertnewRoom" refId="'+(n+1)+'">'));
				EmptyGroupBookRoom();
			}else if(Tabs.type == "Single")
			{
				$("[id*=edit_res_resdetails_checkin_S]").val(new Date($(dateStart).attr("dateform")).getFormatedString());
				$("[id*=edit_res_resdetails_checkout_S]").val(new Date($(dateEnd).attr("dateend")).getFormatedString());
				$("#edit_none_groups_showroomtype").text(getRoomTypeId(Tabs.ResData.roomTypeString).shortName);
				$("#edit_none_groups_cbroom").text(getObjectFromSharedData(SharedData.Room,Tabs.ResData.roomString).roomName);
			}
		}
		showCommandButton(Tabs);
		CalBalancetoShow();
		fillBalanceSingleDetail();
		closeWaitingDialog();
	}
	else if(Tabs.page == "Payment")
	{
		if(Tabs.type == "Group"){
			GroupCalBalancetoShow();
			DisplayGroupPaymentDetail();
		}
		else{
			DisplayPaymentDetail();
			CalBalancetoShow();
			closeWaitingDialog();
		}
	}
}
function fillOwnerInfo(Tabs){
	$('#GName').text("");
	$('#agency_dv').text("");
	$('#GAgent').text("");
	$('#GId_group_code').text("");
	$('#GChkStatus').text("");
	$('[name=groupStatus]').text("");
	
	$("#assaignstatus").html("");
	$('#edit_none_groups_name').text("");
	$('#edit_none_groups_agency').text("");
	$('#edit_none_groups_group_code').text("");
	$('#edit_none_groups_Status').text("");
	$('#edit_none_groups_roomtype').text("");
	getCurrentTab().children().css("background-color","#FFF");
	$("#assaignstatus").html("");
	if(Tabs.Owner == null)
		return;
	
	if(Tabs.type == "Group"){
		$('#GName').text(Tabs.Owner.firstName + " "+ Tabs.Owner.lastName);
		$('#agency_dv').text((Tabs.Agency !=null)?Tabs.Agency.agency:"");
		$('#GAgent').text((Tabs.Agency !=null)?Tabs.Agency.agency:"");
		$('#GId_group_code').text(Tabs.resId);
		$('#GChkStatus').text(Tabs.ResData.GroupStatus);
		$('[name=groupStatus]').text("(G)");
		//$("#editres_status_color").css("background-color",Tabs.guest[0].resColor);
		if(Tabs.ResData.isAssign)
			$("#assaignstatus").html("(A)");
	}
	else if(Tabs.type == "Single")
	{ 
		
		$('#edit_none_groups_name').text(Tabs.Owner.firstName + " "+ Tabs.Owner.lastName);
		if(Tabs.Agency!=null)
			$('#edit_none_groups_agency').text(Tabs.Agency.agency);
		$('#edit_none_groups_group_code').text(Tabs.ResData.id);
		$('#edit_none_groups_Status').text(Tabs.ResData.reservationStatusName);
		$('#edit_none_groups_roomtype').text(Tabs.ResData.roomTypeName);
		$('#edit_none_groups_cbroom').text(Tabs.ResData.roomName);

		var obj = {
			roomTypeId : Tabs.ResData.roomTypeString,
			roomId : Tabs.ResData.roomString,
			from : new Date(getCurrentTabData().ResData.date),
			to : new Date(getCurrentTabData().ResData.dateTo),
			resId :	Tabs.resId
		};
		$('#edit_none_groups_roomtype').unbind('click');
		$('#edit_none_groups_cbroom').unbind('click');
		$('#edit_none_groups_roomtype').click(function(){
			fillRoomDropdown($("#edit_none_groups_cbroom"),$("#edit_none_groups_roomtype"),null,editSingleResvRoomSuccess,null,obj);
		});
		$('#edit_none_groups_cbroom').click(function(){
			fillRoomDropdown($("#edit_none_groups_cbroom"),$("#edit_none_groups_roomtype"),null,editSingleResvRoomSuccess,null,obj);
		});
		if(Tabs.guest != null)
		getCurrentTab().children().css("background-color",Tabs.guest[0].resColor);
		if(Tabs.ResData.isAssign)
			$("#assaignstatus").html("(A)");
	}
}
function editSingleResvRoomSuccess(data,obj)
{
	var objArray = JSON.parse(data);
	if(objArray.EffectedRoom.length > 0)
	{
		cerltimespan(savedSpan);
		closeWaitingDialog();
		finishChangeRoomDropDown(obj);
		for(var i=0;i<objArray.EffectedRoom.length;i++)
			changeRoom(objArray.EffectedRoom[i].id,objArray.EffectedRoom[i].roomId);
		DisplayDetail();
	}
	else
		simpleDialog(messagebox_MoveFail,50,function(){cerltimespan(savedSpan);});
}
function fillOwner(Tabs){
	if(Tabs.showAddguest!= true){
		$('[id=add_insert_guest]').hide();
	}else{
			if(Tabs.showAddguestData==null){$('[id=add_insert_guest]').children().find('input[type=text]').val("");return;}
			$('[id=add_insert_guest]').show();
			$("#insert_solutation").val(Tabs.showAddguestData.salutation);
			$("#insert_name").val(Tabs.showAddguestData.name);
			$("#insert_lastname").val(Tabs.showAddguestData.lastName);
			$("#insert_guestname_phone").val(Tabs.showAddguestData.phone);
			$("#insert_guestname_email").val(Tabs.showAddguestData.mail);
	}
	$('#owner_group').text(addguest_label);
	$('#owner_group_address').text("");
	$('#owner_group_tel').text("");
	$('#company').text("");
	$('#company_address').text("");
	$('#guest_id_edit_res').text("(Guest ID:)");
	$('#edi_res_groups_note').text("");
	
	$('#owner_group_S').text(addguest_label);
	$('#owner_group_address_S').text("");
	$('#owner_group_tel_S').text("");
	$("#guest_id_edit_res_s").text("(Guest ID:)");
	$('#company_S').text("");
	$('#agency_dv_S').text("");
	$('#edi_res_groups_note_S').text("");
	
	if(Tabs.Owner == null)
		return;
	
	if(Tabs.type == "Group"){ 
		(Tabs.Owner.firstName == "" )?$('#owner_group').text(addguest_label):$('#owner_group').text(Tabs.Owner.firstName + " "+ Tabs.Owner.lastName);
		$('#owner_group_address').text(Tabs.Owner.addressLine1);
		$('#owner_group_tel').text(Tabs.Owner.phone);
		$('#company').text(Tabs.Owner.company);
		$('#company_address').text(Tabs.Owner.officeAddress);
		$('#guest_id_edit_res').text("(Guest ID:"+Tabs.Owner.id+")");
		$('#edi_res_groups_note').text(Tabs.ResData.note);
	}else if(Tabs.type == "Single"){
		(Tabs.Owner.firstName == "")?$('#owner_group_S').text(addguest_label):$('#owner_group_S').text(Tabs.Owner.firstName + " "+ Tabs.Owner.lastName);
		$('#owner_group_address_S').text(Tabs.Owner.addressLine1);
		$('#owner_group_tel_S').text(Tabs.Owner.phone);
		$("#guest_id_edit_res_s").text("(Guest ID:"+Tabs.Owner.id+")");
		$('#company_S').text(Tabs.Owner.company);
		$('#agency_dv_S').text(Tabs.ResData.agencyName);
		$('#edi_res_groups_note_S').text(Tabs.ResData.note);
	}
}
function fillCreditCard(Tabs){
	$('[name=edit_res_resdetails_creditcard]').val("");
	$('[name=edit_res_resdetails_creditcard2]').val("");
	$('[name=edit_res_resdetails_creditcard_expire]').val("");
	$('[name=edit_res_resdetails_creditcard2_expire]').val("");
	$('[name=edit_res_resdetails_CVC]').val("");
	$('[name=edit_res_resdetails_creditcard_Id]').val("0");
	$('[name=edit_res_resdetails_creditcard_S]').val("");
	$('[name=edit_res_resdetails_creditcard2_S]').val("");
	$('[name=edit_res_resdetails_creditcard_expire_S]').val("");
	$('[name=edit_res_resdetails_creditcard2_expire_S]').val("");
	$('[name=edit_res_resdetails_CVC_S]').val("");
	$('[name=edit_res_resdetails_creditcard_Id_S]').val("0");
	
	if(Tabs.CreditCard == null)
		return;
	if(Tabs.type=="Group"){
		$('[name=edit_res_resdetails_creditcard]').val(Tabs.CreditCard[0].CardNumber);
		$('[name=edit_res_resdetails_creditcard_expire]').val(Tabs.CreditCard[0].ExpiryDate.split("/")[0]);
		$('[name=edit_res_resdetails_creditcard2_expire]').val(Tabs.CreditCard[0].ExpiryDate.split("/")[1]);
		$('[name=edit_res_resdetails_CVC]').val('XXX');
		$('[name=edit_res_resdetails_creditcard_Id]').val(Tabs.CreditCard[0].id);
	}
	else if(Tabs.type=="Single"){
		$('[name=edit_res_resdetails_creditcard_S]').val(Tabs.CreditCard[0].CardNumber);
		$('[name=edit_res_resdetails_creditcard_expire_S]').val(Tabs.CreditCard[0].ExpiryDate.split("/")[0]);
		$('[name=edit_res_resdetails_creditcard2_expire_S]').val(Tabs.CreditCard[0].ExpiryDate.split("/")[1]);
		$('[name=edit_res_resdetails_CVC_S]').val('XXX');
		$('[name=edit_res_resdetails_creditcard_Id_S]').val(Tabs.CreditCard[0].id);
	}
}
function fillReservationDetailcantEdit(){
	var Tabs = getCurrentTabData();	
	var resData = Tabs.ResData;
	if(Tabs.Owner == null)
		return;
	var sourcesString= (resData.sourcesString !=null)?resData.sourcesString:'';
	var reason= (resData.Objective != null)?resData.Objective:'';
	var objective =(getObjectFromDataIndex(SharedData.SourcesBusiness,"id",sourcesString)!=null)?getObjectFromDataIndex(SharedData.SourcesBusiness,"id",sourcesString).description:"";
			var text="";
			text='<table style="float:left; margin-left:20px;" class="detailtwo">'+
			'<tr>'+
				'<td colspan="3" width="100%">'+
				'<div><b>'+resDetail+'</b></div>'+
				'</td>'+
			'</tr>'+
			'<tr>'+
				'<td width="30%" >'+
				'<div>'+resDetail_checkin+'</div>'+
				'</td>'+
				'<td width="60%">'+
				'<div id="edit_res_resdetails_checkin">'+
				new Date(resData.date).getFormatedString()+'</div></td>'+
				'<td width="10%">&nbsp;</td>'+
			'</tr>'+
			'<tr>'+
				'<td width="30%">'+
				'<div>'+resDetail_checkout+'</div></td>'+
				'<td width="60%">'+
				'<div id="edit_res_resdetails_checkout">'+
				new Date(resData.date).addDate(resData.span).getFormatedString()+'</div></td>'+
				'<td width="10%">&nbsp;</td>'+
			'</tr>'+
			'<tr>'+
				'<td colspan="3">'+
				'<div><div style="float:left;">'+resDetail_duration+'&nbsp;</div><div style="float:left;"><span id="edit_res_resdetails_restime">'+
				resData.span+'</span></div><div>&nbsp;&nbsp;&nbsp;&nbsp;'+resDetail_night+'</div></div></td>'+
			'</tr>'+
			'<tr>'+
				'<td><div>'+resDetail_extrabad+'</div></td><td>'+
				'<div>'+resData.extrabed+'</div>'+
				'</td>'+
				'<td>&nbsp;</td>'+
			'</tr>'+
			'<tr>'+
				'<td><div>'+resDetail_objective+'</div></td><td>'+
				'<div>'+reason+'</div></td>'+
				'<td>&nbsp;</td>'+
			'</tr>'+
			'<tr>'+
				'<td><div>'+resDetail_atcome+'</div></td><td>'+
				'<div>'+objective+'</div></td>'+
				'<td>&nbsp;</td>'+
			'</tr>'+
			'<tr>'+
				'<td colspan="3"><div class="link" name="editDetail" onclick="btnEditReservationDetail()" style="margin-right:10px; float:right;">'+resDetail_edit+'</div></td>'+
			'</tr>'+
		'</table>';
	if(Tabs.type != "Single" ){
		$('[name=editres_staydetail_group]').children().remove();
		$('[name=editres_staydetail_group]').append(text);
	}else{
		$('[name=editres_staydetail_single]').children().remove();
		$('[name=editres_staydetail_single]').append(text);
	}
}

function fillTravelcantEdit(){
	var Tabs = getCurrentTabData();
	var data="";
	(Tabs.type != "Single")?data =Tabs.GroupTravel:data =Tabs.SingleTravel;
	var timeH ="";
	var timeM ="";
	var timeBackH ="";
	var timeBackM="";
	var text ="";
	var tarvelby ="";
	var tarvelbyBack ="";
	var arraive ="";
	var arraiveBack ="";
	if(data!= null){
		arraiveBack =data["arraiveBack"];
		arraive =data["arraive"];
		tarvelby =getObjectFromDataIndex(SharedData.ArrivalMode,"id",data["tarvelby"]).description;
		tarvelbyBack =getObjectFromDataIndex(SharedData.ArrivalMode,"id",data["tarvelbyBack"]).description;
		var timeArraive = data["time"].split(" ");
			var objtimeArrive = timeArraive[3].split(":");
			timeH = objtimeArrive[0];
			timeM = objtimeArrive[1];
			
		var timeBack = data["timeBack"].split(" ");
			var objtimeBack = timeBack[3].split(":");
			timeBackH = objtimeBack[0];
			timeBackM = objtimeBack[1];
	}
	text='<table style="float:left; margin-left:20px;" class="detailtwo" width="100%" name="travelbeforEdit">'+
		'<tr>'+
		'<td colspan="3" width="100%">'+
		'<div><div name="comeBefor" style="float:left; cursor:pointer;" onclick="Changetravelbeforedit()">'+
	    	'<b>'+comeT+'</b></div>'+
	        '<div name="backBefor" style="float:right; color:#999; padding-right:10px; cursor:pointer;" onclick="Changetravelbeforedit()">'+
	        '<b>'+backT+'</b>'+
		'</div></div>'+
		'</td>'+
		'</tr>'+
		'<tr>'+
		'<td colspan="1" width="35%">'+travelBy+' :</td>'+
		'<td width="60%">'+
		'<div name="editres_tarval" style="height:20px; width:150px">'+tarvelby+'</div>'+
		'<div name="editres_tarval_Back" style="height:20px; width:150px; display:none;">'+tarvelbyBack+'</div>'+
		'<div name="editres_resdetails_travelid" style="display:none;"></div>'+
		'</td>'+
		'<td width="5%">&nbsp;</td>'+
		'</tr>'+
		'<tr>'+
		'<td colspan="3">'+
		'<div>'+
		'<div style="float:left;">'+travelArrive+' :</div>'+
		'<div name="editres_arrive" style="width:150px; float:left;">'+arraive+'</div>'+
		'<div name="editres_arrive_Back" style="width:150px; float:left; display:none;">'+arraiveBack+'</div>'+
		'</div>'+
		'</td>'+
		'</tr>'+
		'<tr>'+
		'<td><div style="float:left;">'+timeArrive+' &nbsp;</div></td>'+
		'<td>'+
		'<div style="float:left;" name="timeC">'+
			'<div style="float:left;">'+
	    		'<div style="width:20px;" name="editres_arrivetimeH">'+timeH+'</div>'+
		'</div><span>:</span>'+
	    '<div style="float:right;">'+
			'<div style="width:20px;" name="editres_arrivetimeM">'+timeM+'</div>'+
		'</div>'+
		'</div>'+
		'<div style="float:left; display:none;" name="timeB">'+
			'<div style="float:left;">'+
	    		'<div style="width:20px;" name="editres_BacktimeH">'+timeBackH+'</div>'+
		'</div><span>:</span>'+
		'<div style="float:right;">'+
			'<div type="text" style="width:20px;" name="editres_BacktimeM">'+timeBackM+'</div>'+
		'</div>'+
		'</div>'+
		'</td>'+
		'<td><div>&nbsp;</div></td>'+
		'</tr>'+
		'<tr>'+
		'<td>'+saveTotask+'</td>'+
		'<td>'+
		'<div name="editres_addtask"></div>'+
		'<div name="editres_addtask_Back" style="display:none;"></div>'+
		'</td>'+
		'<td><div>&nbsp;'+
			'<span onclick="btnEditTravelling()" class="link" style="margin-right:10px;">'+btnTedit+'</span></div>'+
		'</td>'+
		'</tr>'+
		'</table>';
	if(Tabs.type != "Group"){
		$('[name=TravelAndArrive_Single]').children().remove();
		$('[name=TravelAndArrive_Single]').append(text);
	}else{
		$('[name=TravelAndArrive_Group]').children().remove();
		$('[name=TravelAndArrive_Group]').append(text);
	}
}

function Changetravelbeforedit(){
	var name = $(event.target).parent().attr('name');
	if(name == "comeBefor"){
		$("[name=backBefor]").css("color","#999");
		$("[name=comeBefor]").css("color","#000");
		$("[name=editres_tarval]").css("display","");
		$("[name=editres_arrive]").css("display","");
		$("[name=timeC]").css("display","");
		$("[name=editres_addtask]").css("display","");
		$("[name=editres_tarval_Back]").css("display","none");
		$("[name=editres_arrive_Back]").css("display","none");
		$("[name=timeB]").css("display","none");
		$("[name=editres_addtask_Back]").css("display","none");
	}
	else if(name == "backBefor"){
		$("[name=comeBefor]").css("color","#999");
		$("[name=backBefor]").css("color","#000");
		$("[name=editres_tarval]").css("display","none");
		$("[name=editres_arrive]").css("display","none");
		$("[name=timeC]").css("display","none");
		$("[name=editres_addtask]").css("display","none");
		$("[name=editres_tarval_Back]").css("display","");
		$("[name=editres_arrive_Back]").css("display","");
		$("[name=timeB]").css("display","");
		$("[name=editres_addtask_Back]").css("display","");
	}
}

function btnEditTravelling(){
	var Tabs = getCurrentTabData();
	var data="";
	(Tabs.type != "Single")?data =Tabs.GroupTravel:data =Tabs.SingleTravel;
	if(Tabs.type != "Group"){
		$('[name=TravelAndArrive_Single]').load('/components/EditReserved/Travel.jsp',function(responseText, textStatus, XMLHttpRequest) {
			if (textStatus == "success") {
				$('[name=TravalSingle]').css('display',"");
				$('[name=travelGroup]').css('display',"none");
				LoadTravelSuccess(data,Tabs.type);
				fillModeArrival();
				if(data != null){
					$("select[id*=edit_none_res_resdetails_tarval]:visible").val(data["tarvelby"]);
					$("select[id*=edit_none_res_resdetails_tarval_Back]").val(data["tarvelbyBack"]);  
				}
				checkElementArea('[name=TravelAndArrive_Single]',function(){SaveTravel()});
			}
		});
	}else{
		$('[name=TravelAndArrive_Group]').load('/components/EditReserved/Travel.jsp',function(responseText, textStatus, XMLHttpRequest) {
			if (textStatus == "success") {
				$('[name=travelGroup]').css('display',"");
				$('[name=TravalSingle]').css('display',"none");
				LoadTravelSuccess(data,Tabs.type);
				fillModeArrival();
				if(data != null){
					$("select[id*=edit_res_resdetails_tarval]:visible").val(data["tarvelby"]);
					$("select[id*=edit_res_resdetails_tarval_Back]:visible").val(data["tarvelbyBack"]); 
				}
				checkElementArea('[name=TravelAndArrive_Group]',function(){SaveTravel()});
			}
		});
	}
}

function AddcreditCard(){
	$("[name=showdialogAddcreditCard]:visible").load('/components/EditReserved/AddCreditCard.jsp',function(responseText, textStatus, XMLHttpRequest) {
		if (textStatus == "success") {
			var title = addcreditCard;
			var content = $("[name=AddcreditCard]").html();
			var size = { width: 485};
			var dialog = customDialog(title,content,size,null,null);
			fillCreditCardType();
			loadnationalityDropDown($('[name=AddcreditCard_country]'));
			$('[name=AddcreditCard_body]:visible').parents('div').children('.ui-newdialog-button').hide();
			ShowOwnCreditCard();
		}
	});
}

function ShowOwnCreditCard(){
	var Tabs = getCurrentTabData();
	var text ="";
	$('[name=Action]:visible').text('');
	if(Tabs.CreditCard !=null){
		$('[name=AccTable_elm]').remove();
		for(var i =0;i<Tabs.CreditCard.length;i++){
			if(Tabs.CreditCard[i].NameOnCard=="")continue;
			text+='<tr name="AccTable_elm">'+
				'<td>'+Tabs.CreditCard[i].NameOnCard+'</td>'+
				'<td>'+Tabs.CreditCard[i].CardNumber+'</td>'+
				'<td>'+getObjectFromSharedData(SharedData.CreditCardType,Tabs.CreditCard[i].CardType).CardTypeName+'</td>'+
				'<td>'+Tabs.CreditCard[i].ExpiryDate+'</td>'+
				'<td><span class="link" delCreditId="'+Tabs.CreditCard[i].id+'" onclick="deleteCreditCrad()">Delete</span></td>'+
				'</tr>';
		}
		$('[name=Action]:visible').text('Action');
		$('[name=AccTable_title]:visible').after(text);
	}
}

function deleteCreditCrad(){
	var creditCardId=$(event.target).attr('delcreditid');
	var link = "/CreditCardService?func=delCreditCard&creditCardId="+creditCardId;
	simpleserviceWithArgs(link,null,deleteCreditCradSuccess,creditCardId);
}

function deleteCreditCradSuccess(data,obj){
var Tabs = getCurrentTabData();
	var objArray = JSON.parse(data);
	if(objArray == null)
		simpleDialog(saveFail_label);
	else
	{
		for(var i=0;i<Tabs.CreditCard.lenght;i++){
			if(Tabs.CreditCard == obj){
				Tabs.CreditCard.splice(i,1);
			}
		}
	}
}

function fillcreditCardcantEdit(){
	var Tabs = getCurrentTabData();
	var text = "";
	if(Tabs.CreditCard==null){
		if(Tabs.type != "Group"){
			$('[name=EditCreditCard_Single]').children().remove();
			$('[name=EditCreditCard_Single]').append(text);
		}else{
			$('[name=EditCreditCard_Group]').children().remove();
			$('[name=EditCreditCard_Group]').append(text);
		}
		return;
	}
	if(Tabs.CreditCard!=null){
		text+='<div><span style="margin-right:20px;">'+creditCardDetail+'</span><span class="link" onclick="viewAllCreditCard()">('+creditCardDetail_viewAll+')</span></div>'+
			'<div><span style="margin-right:80px;">'+Tabs.CreditCard[0].CardNumber+'</span>'+
			'<span>'+getObjectFromSharedData(SharedData.CreditCardType,Tabs.CreditCard[0].CardType).CardTypeName+'</span></div>'+
			'<div><span>'+creditCardDetail_ex+'</span><span style="margin-right:80px;">'+Tabs.CreditCard[0].ExpiryDate+'</span>'+
			'<span>CVC:</span><span>XXX</span></div>'+
			'<div class="link" onclick="btnEditCreditCard()" style="margin-right:10px; float:right;">'+resDetail_edit+'</div>';
	}
	if(Tabs.type != "Group"){
		$('[name=EditCreditCard_Single]').children().remove();
		$('[name=EditCreditCard_Single]').append(text);
	}else{
		$('[name=EditCreditCard_Group]').children().remove();
		$('[name=EditCreditCard_Group]').append(text);
	}
}

function viewAllCreditCard(){
	var Tabs = getCurrentTabData();
	var text ="";
	if(Tabs.CreditCard !=null){
		for(var i =0;i<Tabs.CreditCard.length;i++){
			text+='<tr name="viewAll_creditCard">'+
				'<td>'+Tabs.CreditCard[i].NameOnCard+'</td>'+
				'<td>'+Tabs.CreditCard[i].CardNumber+'</td>'+
				'<td>'+getObjectFromSharedData(SharedData.CreditCardType,Tabs.CreditCard[i].CardType).CardTypeName+'</td>'+
				'<td>'+Tabs.CreditCard[i].ExpiryDate+'</td>'+
				'</tr>';
		}
	}
	var content = '<table width="100%">'+
					'<tr name="AccTable_title">'+
					'<td width="30%">'+ACC_name+'</td>'+
					'<td width="40%">'+ACC_Cn+'</td>'+
					'<td width="15%">'+ACC_type+'</td>'+
					'<td width="15%">'+ACC_Expiry+'</td>'+
					'</tr>'+text+'</table>';
	var buttons = [
		{ title:"OK" , callback: function(thisdialog,args){
			thisdialog.dialog("close");
		}}
	];
	customDialog(creditCardDetail_viewAll,content,{ width:600},buttons,null);
	//$('[name=AddcreditCard_body]:visible').parents('div').children('.ui-newdialog-button').show();
}

function btnEditCreditCard(){
	var Tabs = getCurrentTabData();
	if(Tabs.type != "Group"){
		$("[name=EditCreditCard_Single]").load('/components/EditReserved/CreditCard.jsp',function(responseText, textStatus, XMLHttpRequest) {
			if (textStatus == "success") {
				$('[name=creditCardGroup]').css('display','none');
				$('[name=creditCardSingle]').css('display','');
				fillCreditCard(Tabs);
				fillCreditCardType();
				$('[name=edit_res_resdetails_creditcard2_S]:visible').val(Tabs.CreditCard[0].CardType);
				checkElementArea('[name=EditCreditCard_Single]',function(){saveCreditCard()});
			}
		});
	}else{
		$("[name=EditCreditCard_Group]").load('/components/EditReserved/CreditCard.jsp',function(responseText, textStatus, XMLHttpRequest) {
			if (textStatus == "success") {
				$('[name=creditCardGroup]').css('display','');
				$('[name=creditCardSingle]').css('display','none');
				fillCreditCard(Tabs);
				fillCreditCardType();
				$('[name=edit_res_resdetails_creditcard2]:visible').val(Tabs.CreditCard[0].CardType);
				checkElementArea('[name=EditCreditCard_Group]',function(){saveCreditCard()});
			}
		});
	}
}

function checkBeforAddCreditCard(){
	if($('[name=AddCC_NOC]:visible').val() ==""){
		simpleDialog("please fill Name on card.");
		return false;
	}
	if(!$.isNumeric($('[name=AddCC_CCN]:visible').val()) && $('[name=AddCC_CCN]:visible').val().length != 16){
		simpleDialog("please fill Cred number.");
		return false;
	}
	if($('[name=addcreditCard_type]:visible').val()==""){
		simpleDialog("please select Card type.");
		return false;
	}
	if(!$.isNumeric($('[name=AddCC_MM]:visible').val()) && $('[name=AddCC_MM]:visible').val().length >2){
		simpleDialog("please fill Month.");
		return false;
	}
	if(!$.isNumeric($('[name=AddCC_MM]:visible').val()) && $('[name=AddCC_YY]:visible').val().length !=4){
		simpleDialog("please fill Name on Year.");
		return false;
	}
	if($('[name=AddCC_CVC]:visible').val() =="" && $('[name=AddCC_CVC]:visible').val().length !=3){
		simpleDialog("please fill CVC");
		return false;
	}
	if($('[name=AddCC_Address]:visible').val()==""){
		simpleDialog("please fill Address");
		return false;
	}
	if($('[name=AddCC_state]:visible').val()==""){
		simpleDialog("please fill State");
		status= false;
	}
	if($('[name=AddcreditCard_country]:visible').val() =="-"){
		simpleDialog("please select Country");
		return false;
	}
	if($('[name=AddCC_City]:visible').val()==""){
		simpleDialog("please fill City");
		return false;
	}
	if(!$.isNumeric($('[name=AddCC_Zipcode]:visible').val())){
		simpleDialog("please fill Zipcode");
		return false;
	}
	return true;
}

function AddCreditCardtoEntity(){
	if(!checkBeforAddCreditCard()){return;}
	var Tabs = getCurrentTabData();
	var guestId =Tabs.Owner.id;
	var nameOnCard =$('[name=AddCC_NOC]:visible').val();
	var creditCardNum =$('[name=AddCC_CCN]:visible').val();
	var cardType =$('[name=addcreditCard_type]:visible').val();
	var expire =$('[name=AddCC_MM]:visible').val()+"/"+$('[name=AddCC_YY]:visible').val();
	var CVC =$('[name=AddCC_CVC]:visible').val();
	var Address =$('[name=AddCC_Address]:visible').val();
	var state =$('[name=AddCC_state]:visible').val();
	var country =($("[name=AddcreditCard_country]:visible").find(':selected').val() !="-")?$("[name=AddcreditCard_country]:visible").find(':selected').text():"";
	var City =$('[name=AddCC_City]:visible').val();
	var Zipcode =$('[name=AddCC_Zipcode]:visible').val();
	var link = "/CreditCardService?func=addFullCreditCard&nameoncard="+nameOnCard+"&cardnumber="+creditCardNum
	+"&cardtype="+cardType+"&expiredate="+expire+"&cvc="+CVC+"&address="+Address+"&state="+state+"&country="+country+"&city="+City+"&zipcode="+Zipcode+"&guestId="+guestId;
	simpleserviceWithArgs(link,null,LoadAddCreditCardSuccess,null);
}

function LoadAddCreditCardSuccess(data,obj){
	var objArray = JSON.parse(data);
	if(objArray == null)
		simpleDialog(saveFail_label);
	else
	{
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut){
			fillCreditCardnoPayment();
			fillcreditCardcantEdit();
			return;
		}
		var Tabs= getCurrentTabData();
		if(Tabs.CreditCard !=null){
			Tabs.CreditCard.push(JSON.parse(data));
		}else{
		var cardAry=[];
		cardAry.push(JSON.parse(data));
			Tabs.CreditCard =cardAry;
		}
		$('[name=AddcreditCard_body]:visible').parents('#BlankDialog').dialog('close');
		
		if(Tabs.page=="Payment"){
			var valSlt=objArray.id;
			fillCreditCardnoPayment(valSlt);
		}
		fillcreditCardcantEdit();
	}
}

function fillReservationDetail(Tabs){
	var resData = getCurrentTabData().ResData;
	$("[id*=edit_res_resdetails_objective]:visible").val("");
	$("[id*=edit_res_resdetails_checkin]:visible").val("");
	$("[id*=edit_res_resdetails_checkout]:visible").val("");
	$("[id*=edit_res_resdetails_restime]:visible").html("");
	$("[id*=edit_res_resdetails_extarbed]:visible").find("option").remove();
	if(resData == null)
		return;
	$("[id*=edit_res_resdetails_checkin]:visible").val(new Date(resData.date).getFormatedString());
	$("[id*=edit_res_resdetails_checkout]:visible").val(new Date(resData.date).addDate(resData.span).getFormatedString());
	$("[id*=edit_res_resdetails_restime]").html(resData.span);
	
	$("[id*=edit_res_resdetails_extarbed]:visible").find("option").remove();
	var Tabs = getCurrentTabData();
	var roomTypeId = (Tabs.type == "Group")? Tabs.ResData.roomtypeString : Tabs.ResData.roomTypeString;
	var roomType = getObjectFromSharedData(SharedData.RoomType,roomTypeId);
	var maxextrabed = roomType.extraBedAllowed;
	if(maxextrabed > roomType.extraBedAllowed) maxextrabed = roomType.extraBedAllowed;
	for(var i=0;i<=maxextrabed;i++)
		$("[id*=edit_res_resdetails_extarbed]:visible").append(optionString.format(i,i));
	$("[id*=edit_res_resdetails_extarbed]:visible").val(resData.extrabed);
	$("[id*=edit_res_resdetails_objective]:visible").val(resData.Objective);
}
function fillPackageTable()
{
	var Tabs = getCurrentTabData();
	var pacList =Tabs.PacByDate;
	if(pacList == null)
		return;
	$("#package_rate_edit_res").find("tr").not(":first").remove();
	pacList.sort(function(a, b) {return new Date(a.dateFrom) - new Date(b.dateFrom)})
	for(var i=0;i<pacList.length;i++)
	{
		var str = '<tr style="height:24px;" refId="{0}">' +
				'<td><div name="roomrate_typepricerate" class="link" refId="{1}" style="margin-left:20px;">{2}</div></td>' +
				'<td><span name="roomrate_date_StartDate">{3}</span>&nbsp;-&nbsp;<span name="roomrate_date_endDate" class="link">{4}</span>' +
				'<td style="text-align:right;">{5}</td>' +
				'<td style="text-align:center;">{6}</td>'
			'</tr>';
		var df = new Date(pacList[i].dateFrom);
		var dt = new Date(pacList[i].dateTo);
		var charge = 0.0;
		for(var j=0;j<Tabs.ChargeList.length;j++)
		{
			var cd = new Date(Tabs.ChargeList[j].chargeDate);
			if(Tabs.ChargeList[j].isRoomCharge && cd>=df && cd<dt)
				charge+=Tabs.ChargeList[j].chargeAmount;
		}
			
		$("#package_rate_edit_res").find("tr:last-child").after(
			str.format(
				pacList[i].id,
				pacList[i].packageString,
				getObjectFromSharedData(SharedData.Package,pacList[i].packageString).Name,
				df.getFormatedString(),
				dt.getFormatedString(),
				"<span class='link' onclick='fillSimpleTextEdit($(this),true,editPackagePrice);'>" + toCurrencyString(charge) + "</span>",
				daysBetween(df,dt)
			)
		);		
	}
	ShowCalendar();
	changePackage();
}

function fillRoomDetailandGuestAmount(){
	var Tabs = getCurrentTabData();
	var rooms =Tabs.GroupResvList;
	if(rooms == null)return;
	var adult=0;
	var child=0;
	var night=0;
	$('#editreserved_checkin_amount:visible').html(rooms.length);
	for(var i = 0;i<rooms.length;i++)
	{
		adult+=parseInt(rooms[i].ResData.adult);
		child+=parseInt(rooms[i].ResData.child);
		night+=parseInt(rooms[i].ResData.span);
	}
	$('#editreserved_adlut_amount:visible').html(adult);
	$('#editreserved_children_amount:visible').html(child);
	$('#editreserved_roomrent_amount:visible').html(child+adult);
	$('.editreserved_checkin_amount:visible').html(night);
	
}
function btnEditReservationDetail(){
	var Tabs = getCurrentTabData();
	if(Tabs.type != "Single"){
		$("[name=editres_staydetail_group]").load('/components/EditReserved/ReservationDetail.jsp',function(responseText, textStatus, XMLHttpRequest) {
			if (textStatus == "success") {
				$('[name=resDetailGroup]').css('display',"");
				$('[name=resDetailSingle]').css('display',"none");
				fillReservationDetail(Tabs);
				fillSourceBuss();
				$("[id*=edit_res_resdetails_provenance]:visible").val(Tabs.ResData.sourcesString);
				checkElementArea('[name=editres_staydetail_group]',function(){SavedetailG()});
			}
		});
	}else{
		$("[name=editres_staydetail_single]").load('/components/EditReserved/ReservationDetail.jsp',function(responseText, textStatus, XMLHttpRequest) {
			if (textStatus == "success") {
				$('[name=resDetailSingle]').css('display',"");
				$('[name=resDetailGroup]').css('display',"none");
				fillReservationDetail(Tabs);
				fillSourceBuss();
				$("[id*=edit_res_resdetails_provenance]:visible").val(Tabs.ResData.sourcesString);
				checkElementArea('[name=editres_staydetail_single]',function(){SavedetailS()});
			}
		});
	}
}

function editPackagePrice(obj){
	if(!$.isNumeric(obj.textbox.val()))
		simpleDialog(WarningMessage_FillNumber);
	else{
		if(currencyStringToNumber(obj.dom.html()) == Number(obj.textbox.val()))
			return;
		var data = { doClass : "EditPackageCustomPrice",
				resId : getCurrentTabData().resId,
				packageByDateId: obj.dom.parents("tr:first").attr("refid"),
				price: obj.textbox.val()
			}
		waitingDialog({});
		simpleserviceWithArgs("/packageService",data,function(data,obj){
			closeWaitingDialog();
			var objArray = JSON.parse(data);
			var checkLogOut =  CheckSession(objArray);
			if(checkLogOut)
				return;
			getCurrentTabData().ChargeList = objArray.charge;
			DisplayDetail();
		},obj);
	}
}

function showCommandButton(Tabs)
{
	var cmdButton = $(".command_button:visible input[type='button']");
	cmdButton.css("display","none");
	if(sortDateCancelPolicy()!=null){
	var canPolicyTime =sortDateCancelPolicy()[sortDateCancelPolicy().length-1];
	}
	if(Tabs.resId == 0)
	{
		if(Tabs.type == "Single"&&Tabs.page=="Detail")
		{
			$(".command_button:visible [name=tempReservation]").show();
			$(".command_button:visible [name=reservation]").show();
			$(".command_button:visible [name=earyCheckin]").show();
			$(".command_button:visible [name=checkin]").show();
			$(".command_button:visible [name=payMent]").show();
			$(".command_button:visible [name=closeSingle]").show();			
		}
		else if(Tabs.type == "Group"&&Tabs.page=="Detail")
		{
			var element = false;
			$("[name=edit_res_detail_rooms] span").each(function(){
				if($("[name=edit_res_detail_rooms] span").attr("roomid")!= "0")
					return element=true;
			});
			if(element == false)
			{
				$(".command_button:visible [name=GrouptempReservation]").show();
			}
			$(".command_button:visible [name=reservationGroup]").show();
			$(".command_button:visible [name=checkinGroup]").show();
			$(".command_button:visible [name=Grouppayment]").show();
			$(".command_button:visible [name=closeGroup]").show();	
		}
	}
	else if(Tabs.resId != 0)
	{
		if(Tabs.type == "Single")
		{
			var status = Tabs.ResData.reservationStatusName;
			 if(Tabs.fromGroupId != null && Tabs.page=="Detail" && status == "Temp Rooms")
				{
					$(".command_button:visible [name=backToGroup]").show();
					$(".command_button:visible [name=reservation]").show();
					if(getEarlyCheckin()){
					$(".command_button:visible [name=earyCheckin]").show();
					}
					$(".command_button:visible [name=checkin]").show();
					$(".command_button:visible [name=CancelReservation]").show();
					$(".command_button:visible [name=payMent]").show();
					$(".command_button:visible [name=closeSingle]").show();	
				}
			 else if(Tabs.page=="Detail"&&status == "Temp Rooms"){
				$(".command_button:visible [name=reservation]").show();
				if(getEarlyCheckin())
					$(".command_button:visible [name=earyCheckin]").show();
				$(".command_button:visible [name=checkin]").show();
				$(".command_button:visible [name=CancelReservation]").show();
				$(".command_button:visible [name=payMent]").show();
				$(".command_button:visible [name=closeSingle]").show();	
				}
			 else if(Tabs.page=="Detail"&&status == "Reserved Rooms"){
				 
				 	if(Tabs.fromGroupId != null&&getServerDateTime().getTime()<=canPolicyTime.getTime())
					{
						$(".command_button:visible [name=backToGroup]").show();
						if(getEarlyCheckin()){
							$(".command_button:visible [name=earyCheckin]").show();
					}
					$(".command_button:visible [name=checkin]").show();
					$(".command_button:visible [name=CancelReservation]").show();
					$(".command_button:visible [name=payMent]").show();
					$(".command_button:visible [name=closeSingle]").show();	
				}
				else if(getServerDateTime().getTime()<=canPolicyTime.getTime())
				{
					if(getEarlyCheckin())
						$(".command_button:visible [name=earyCheckin]").show();
					$(".command_button:visible [name=checkin]").show();
					$(".command_button:visible [name=CancelReservation]").show();
					$(".command_button:visible [name=payMent]").show();
					$(".command_button:visible [name=closeSingle]").show();	
				}
				if(Tabs.fromGroupId != null&&getServerDateTime().getTime()>canPolicyTime.getTime())
				{
					$(".command_button:visible [name=backToGroup]").show();
					if(getEarlyCheckin())
						$(".command_button:visible [name=earyCheckin]").show();
					$(".command_button:visible [name=checkin]").show();
					$(".command_button:visible [name=chargeNoShow]").show();
					$(".command_button:visible [name=CancelReservation]").show();
					$(".command_button:visible [name=payMent]").show();
					$(".command_button:visible [name=closeSingle]").show();	
				}
				else if(getServerDateTime().getTime()>canPolicyTime.getTime())
				{
					if(getEarlyCheckin())
						$(".command_button:visible [name=earyCheckin]").show();
					$(".command_button:visible [name=checkin]").show();
					$(".command_button:visible [name=chargeNoShow]").show();
					$(".command_button:visible [name=payMent]").show();
					$(".command_button:visible [name=closeSingle]").show();	
				 } 
			 }
			 else if(Tabs.page=="Detail"&&status =="Checked-in Rooms")
			 {
				 if(Tabs.fromGroupId != null && Tabs.ResData.EarlyCheckout && getServerDateTime().getTime()< getEarlyCheckOut().getTime())
					{
					 $(".command_button:visible [name=backToGroup]").show();
					 $(".command_button:visible [name=checkOut]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();	
					}
				 else if(Tabs.ResData.EarlyCheckout && getServerDateTime().getTime()< getEarlyCheckOut().getTime())
				 	{
					 $(".command_button:visible [name=checkOut]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();	
				 	} 
				 
				 if(Tabs.fromGroupId != null&&getServerDateTime().getTime()< getEarlyCheckOut().getTime())
					{
					 $(".command_button:visible [name=backToGroup]").show();
					 $(".command_button:visible [name=cancelCheckin]").show();
					 $(".command_button:visible [name=earyCheckOut]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();	
					}
				 else if(getServerDateTime().getTime()< getEarlyCheckOut().getTime())
				 	{
					 $(".command_button:visible [name=cancelCheckin]").show();
					 $(".command_button:visible [name=earyCheckOut]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();	
				 	} 
				 if(Tabs.fromGroupId != null&&getServerDateTime().getTime()>= getEarlyCheckOut().getTime())
					{
					 $(".command_button:visible [name=backToGroup]").show();
					 $(".command_button:visible [name=checkOut]").show();
					 $(".command_button:visible [name=latecheckOut]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();	
					}
				 else if(getServerDateTime().getTime()>= getEarlyCheckOut().getTime())
				 	{
					 
					 $(".command_button:visible [name=checkOut]").show();
					 $(".command_button:visible [name=latecheckOut]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();	
				 	} 
				 
				 if(Tabs.ResData.lateCheckout &&  getServerDateTime().getTime()>= getEarlyCheckOut().getTime())
				 {
					 if(Tabs.fromGroupId != null)
						{
						 $(".command_button:visible [name=backToGroup]").show();
						 $(".command_button:visible [name=checkOut]").show();
						 $(".command_button:visible [name=payMent]").show();
						 $(".command_button:visible [name=closeSingle]").show();	
						}
					 else
						{
						 $(".command_button:visible [name=checkOut]").show();
						 $(".command_button:visible [name=payMent]").show();
						 $(".command_button:visible [name=closeSingle]").show();	
						}
				 }
			 }
			 else if (Tabs.page=="Detail"&&status =="Checked-out Rooms")
			 {
				 if(Tabs.fromGroupId != null&&getServerDateTime().getTime()< getEarlyCheckOut().getTime())
				 {
					 $(".command_button:visible [name=backToGroup]").show();
					 $(".command_button:visible [name=cancelCheckOut]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();
				 }
				 else if(getServerDateTime().getTime()< getEarlyCheckOut().getTime())
				 {
					 $(".command_button:visible [name=cancelCheckOut]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();
				 }
				 
				 if(Tabs.fromGroupId != null&&getServerDateTime().getTime()>= getEarlyCheckOut().getTime())
				 {
					 $(".command_button:visible [name=backToGroup]").show();
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();
				 }
				 else if(getServerDateTime().getTime()>= getEarlyCheckOut().getTime())
				 {
					 $(".command_button:visible [name=payMent]").show();
					 $(".command_button:visible [name=closeSingle]").show();
				 }
			 }
		}
		else if(Tabs.type == "Group")
		{
			
			var GroupStatus =Tabs.ResData.GroupcheckStauts;
			if(Tabs.page=="Detail"&&GroupStatus == "Temp Rooms")
			{
				$(".command_button:visible [name=reservationGroup]").show();
				$(".command_button:visible [name=Groupcancellation]").show();
				$(".command_button:visible [name=Groupcheckin]").show();
				$(".command_button:visible [name=Grouppayment]").show();
				$(".command_button:visible [name=closeGroup]").show();	
			}	
			else if(Tabs.page=="Detail"&&GroupStatus == "Reserved Rooms"&&getServerDateTime().getTime()<=canPolicyTime.getTime())
			{
				$(".command_button:visible [name=Groupcancellation]").show();
				$(".command_button:visible [name=checkinGroup]").show();
				$(".command_button:visible [name=Grouppayment]").show();
				$(".command_button:visible [name=closeGroup]").show();	
						
			}
			else if(Tabs.page=="Detail"&&GroupStatus == "Reserved Rooms"&&getServerDateTime().getTime()>canPolicyTime.getTime())
			{
				$(".command_button:visible [name=groupNoShow]").show();
				$(".command_button:visible [name=checkinGroup]").show();
				$(".command_button:visible [name=Grouppayment]").show();
				$(".command_button:visible [name=closeGroup]").show();	
						
			}
			else if(Tabs.page=="Detail"&&GroupStatus =="Checked-in Rooms"&&getServerDateTime().getTime()< getEarlyCheckOut().getTime())
		 	{
				if(Tabs.ResData.lateCheckout)
				{
					$(".command_button:visible [name=checkOutGroup]").show();
					$(".command_button:visible [name=Grouppayment]").show();
					$(".command_button:visible [name=closeGroup]").show();
				}else{
					$(".command_button:visible [name=Grouppayment]").show();
					$(".command_button:visible [name=closeGroup]").show();
				}
		 	}
			else if(Tabs.page=="Detail"&&GroupStatus =="Checked-in Rooms"&&getServerDateTime().getTime()>= getEarlyCheckOut().getTime())
		 	{
					$(".command_button:visible [name=checkOutGroup]").show();
					$(".command_button:visible [name=latecheckOutGroup]").show();
					$(".command_button:visible [name=Grouppayment]").show();
					$(".command_button:visible [name=closeGroup]").show();
		 	}
			else if (Tabs.page=="Detail"&&GroupStatus =="Checked-out Rooms"&&getServerDateTime().getTime()< getEarlyCheckOut().getTime())
				 {
					 $(".command_button:visible [name=GroupcancelCheckOut]").show();
					 $(".command_button:visible [name=Grouppayment]").show();
					 $(".command_button:visible [name=closeGroup]").show();	
				 }
			else if (Tabs.page=="Detail"&&GroupStatus =="Checked-out Rooms"&&getServerDateTime().getTime()>= getEarlyCheckOut().getTime())
			{
				 $(".command_button:visible [name=Grouppayment]").show();
				 $(".command_button:visible [name=closeGroup]").show();
			 }
		}
		
	}
}

function ChangToEdit(id)
{
	ShowManageGuestDialog();
}

function changePackage()
{
	$("[name*=roomrate_typepricerate]").click(function(e){
		var Dom =$(e.srcElement);
		fillSimpleDropdown(Dom,SharedData.Package,'id','Name',LoadPackageSuccess);
	});
}


function  LoadPackageSuccess(obj)
{
	var Tabs =getCurrentTabData();
	var resId =Tabs.resId;
	var pacId =obj.select.find(":selected").val();
	var pacByDateId =obj.dom.parents("tr:first").attr("refid");
	var rawFormDate =obj.dom.parents("tr:first").find("[name=roomrate_date_StartDate]").text();
	var rawToDate =obj.dom.parents("tr:first").find("[name=roomrate_date_endDate]").text();
	var DateF = rawFormDate.getDate().toSystemFormat();
	var DateT = rawToDate.getDate().toSystemFormat();
	
	var link = "/packageService?doClass=editPackageByDate&packageId="+pacId+"&pacByDateId="+pacByDateId
		+"&dateForm="+DateF+"&dateTo="+DateT+"&resId="+resId;
	waitingDialog({});
	simpleserviceWithArgs(link,null,ChargePackageSuccess,obj);
}
function ChargePackageSuccess(data,obj)
{
	closeWaitingDialog();
	var objArray = JSON.parse(data);
	if(objArray  == null)
		simpleDialog(saveFail_label,1000);
	else
	{
		var checkLogOut =  CheckSession(objArray);
		if(checkLogOut)
			return;
		var Tabs = getCurrentTabData();
		Tabs.PacByDate = objArray.packageByDate;
		Tabs.ChargeList = objArray.charge;
		
		var packagenamelist = filedListOfList(objArray.packageByDate,["packages","Name"]);
		var packagename = "";
		for(j=0;j<packagenamelist.length;j++)
			if(packagename == "") packagename = packagenamelist[j];
			else if($.trim(packagename) != $.trim(packagenamelist[j])) packagename = "Multiple Package";
		Tabs.ResData.priceRateName = packagename;
		Tabs.ResData.priceRateString = filedStringOfList(objArray.packageByDate,["id"]);
		Tabs.ResData.pricePackageId = (packagename == "Multiple Package")? "" : objArray.packageByDate[0].packageString;
		fillPackageTable();
	}
}

//CalData
function CalExtrabed()
{
	var roomTypeId = (Tabs.type == "Group")? Tabs.ResData.roomtypeString : Tabs.ResData.roomTypeString;
	var roomType = getObjectFromSharedData(SharedData.RoomType,roomTypeId);
	var guest = getCurrentTabData().guest.length;
	
	var extrabed = 0;
	if(guest > roomtype.StandardOccupancy)
	{
		extrabed = guest - roomtype.StandardOccupancy;
		if(extrabed > roomtype.extraBedAllowed)
			extrabed = roomtype.extraBedAllowed;
	}
	$("[id*=edit_res_resdetails_extarbed]").val(extrabed);
}

//Split
function EditSplitReservationRoom(dom)
{
	var domRoom = dom.find("td[name='room'] div");
	var domRoomType = dom.find("td[name='roomtype'] div");
	fillRoomDropdown(domRoom,domRoomType,dom,editSplitedRoomSuccess);
}
function editSplitedRoomSuccess(data,obj)
{
	var objArray = JSON.parse(data);
	var checkLogOut =  CheckSession(objArray);
	if(checkLogOut)
		return;
	if(objArray.EffectedRoom.length > 0)
	{
		cerltimespan(savedSpan);
		closeWaitingDialog();
		finishChangeRoomDropDown(obj);
			
		for(var i=0;i<objArray.EffectedRoom.length;i++)
			changeRoom(objArray.EffectedRoom[i].id,objArray.EffectedRoom[i].roomId);

		var Tabs = getCurrentTabData();
		ResetChargeList(objArray.ChargeList,Tabs);
		DisplayDetail();
	}
	else
		simpleDialog(messagebox_MoveFail,50,function(){cerltimespan(savedSpan);});
}

function formatTextArea(textArea) {
	textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
}

function showResvList(Tabs){
	$("#resvList").find("tr").not($("#resvList").find("tr").first()).remove();
	var itemTemp = '<tr resId="{0}" from="{13}" to="{14}">' +
		'<td><div name="edit_res_detail_atcount">{1}<input type="checkbox" name="edit_res_detail_at"></div></td>' +
		'<td><div name="edit_res_detail_resid">{2}</div></td>' +
		'<td><div name="edit_res_detail_roomtype">{3}</div></td>' +
		'<td><div name="edit_res_detail_rooms">{4}</div></td>' +
		'<td><div name="edit_res_detail_guestname">{5}</div></td>' +
		'<td><div name="edit_res_detail_phone">{6}</div></td>' +
		'<td><div name="edit_res_detail_guestamount">{7}</div></td>' +
		'<td><div name="edit_res_detail_status">{8}</div></td>' +
		'<td><div name="edit_res_detail_checkinstatus">{9}</div></td>' +
		'<td><div name="edit_res_detail_night">{10}</div></td>' +
		'<td><div name="edit_res_detail_rate">{11}</div></td>' +
		'<td><div name="edit_res_detail_price">{12}</div></td>' +
		'</tr>';
	if(Tabs.resId == 0 ||Tabs.GroupResvList.length == 0 )
		$("#resvList").find("tr:last").after(itemTemp.format(0,1,'&nbsp;','&nbsp;','&nbsp;','&nbsp;','&nbsp;','&nbsp;','&nbsp;','&nbsp;','&nbsp;','&nbsp;','&nbsp;',0,0,"&nbsp;","&nbsp;"));
	else
		for(var i=0;i<Tabs.GroupResvList.length;i++){
			var data = Tabs.GroupResvList[i].ResData;
			var guestId = data.guestString;
			var roomStyle = (data.roomString != "MultipleRoom")? "class='link' onclick='GroupResvListEditRoom($(this));'" : "";
			var occupancystyle = (data.roomString != "MultipleRoom")? "class='link' onclick='changeGroupResvListOccupancy($(this));'" : "";
			var packagename = "";
			var packagenamelist = filedListOfList(Tabs.GroupResvList,["ResData","priceRateName"]);
			var total = 0;
			if(Tabs.GroupResvList[i].ChargeList!=null)
			for(var j=0;j<Tabs.GroupResvList[i].ChargeList.length;j++) total+=Tabs.GroupResvList[i].ChargeList[j].chargeAmount;
			$("#resvList").find("tr:last").after(itemTemp.format(
				data.id,
				i+1,
				"<span class='link' onclick='displaySingleRoomInGroup($(this));'>" + data.id + "</span>",
				"<span "+roomStyle+" roomtypeId='" +data.roomTypeString+ "'>" + data.roomTypeName + "</span>",
				"<span "+roomStyle+" roomId='" +data.roomString+ "'>" + data.roomName + "</span>",
				(guestId == 0)? '<span guestid="'+guestId+'"  class="link" onclick="showManageResinGroupGuest(this)">'+addGuest_label+'</span>' :'<span guestid="'+guestId+'">'+data.guestName+" "+data.guestLastName+'</span><span class="brushimg" onclick="Clearguest(this)"></span>',
				(guestId == 0)? "&nbsp;" :data.guestTel,
				"<span name='adult' refId='"+data.adult+"' "+occupancystyle+">"+data.adult + "</span> - <span name='child' refId='"+data.child+"' "+occupancystyle+">"+data.child + "</span>",
				getLocalizeResvStatus(data.reservationStatusName),
				"<span class='link' name='checkin' onclick='SelectDateTimePicker(this,\"top\",getDate(),null,editResvInGroupCheckIn);'>"+new Date(data.date).getFormatedString() + "</span> - <span class='link' name='checkout' onclick='SelectDateTimePicker(this,\"top\",getResvInGroupCheckInDate(this),null,editResvInGroupCheckOut);'>" + new Date(data.date).addDate(data.span).getFormatedString() + "</span>",
				data.span,
				(data.priceRateName!="Multiple Package")?"<span class='link' refId='"+data.pricePackageId+"' pByDate='"+data.priceRateString+"' onclick='changeGroupPackage($(this));'>"+data.priceRateName+"</span>":data.priceRateName,
				"<span class='link' onclick='changeGroupPrice($(this));'>"+toCurrencyString(total)+"</span>",
				new Date(data.date),
				new Date(data.date).addDate(data.span)
			));
		}
}
function changeGroupPrice(dom){
	fillSimpleTextEdit(dom,true,function(obj){
		var link = "/packageService?doClass=editPricePackByDateFromGroup&price="+obj.textbox.val()+"&resId="+obj.dom.parents("tr").attr("resid")
		waitingDialog({});
		simpleserviceWithArgs(link,null,function(data,obj){
			var chargelist = JSON.parse(data);
			if(chargelist.length == 0)
				simpleDialog("");
			else{
				var checkLogOut = CheckSession(objArray);
				if(checkLogOut)
					return;
				var resId = obj.dom.parents("tr:first").attr("resid");
				var resv = getObjectFromDataIndex(getCurrentTabData().GroupResvList,"resId",resId);
				for(i=0;i<chargelist.length;i++)
				{
					var charge = getObjectFromSharedData(resv.ChargeList,chargelist[i].id);
					charge.chargeAmount = chargelist[i].amount;
					charge.discount = chargelist[i].discount;
					charge.tax = chargelist[i].tax;
				}
				showResvList(getCurrentTabData());
				closeWaitingDialog();
			}
		},obj);
	});
}
function changeGroupPackage(Dom)
{
	fillSimpleDropdown(Dom,SharedData.Package,'id','Name',function(obj){
		var pac = obj.select.find(":selected").val();
		var link = "/packageService?doClass=editPackageByDateFromGroup&packageId="+pac+"&pacByDateId="+obj.dom.attr("pbydate")+"&resId="+obj.dom.parents("tr").attr("resid");
		waitingDialog({});
		simpleserviceWithArgs(link,null,function(data,obj){
			var objArray = JSON.parse(data);
			var checkLogOut =  CheckSession(objArray);
			if(checkLogOut)
				return;
			var resId = obj.dom.parents("tr:first").attr("resid");
			var res = getObjectFromDataIndex(getCurrentTabData().GroupResvList,"resId",resId);
			res.ResData.pricePackageId = obj.select.find(":selected").val();
			res.ResData.priceRateName = obj.select.find(":selected").text();
			var chargelist = JSON.parse(data);
			for(i=0;i<chargelist.length;i++)
			{
				var charge = getObjectFromSharedData(res.ChargeList,chargelist[i].id);
				charge.chargeAmount = chargelist[i].amount;
				charge.discount = chargelist[i].discount;
				charge.tax = chargelist[i].tax;
			}
			showResvList(getCurrentTabData());
			closeWaitingDialog();
		},obj);
	});
}


function editResvInGroupCheckIn(val,dom,isChanged){
	if(!isChanged) return;
	var res = dom.parents("tr:first");
	var checkout = res.find("[name=checkout]");
	var checkoutVal = checkout.html().getDate();
	if(val.getDate() > checkout.html().getDate())
		checkoutVal = val.getDate();
	editResvInGroupCheckInCheckOut(dom,val.getDate(),checkoutVal);
}
function getResvInGroupCheckInDate(e){var t=$(e).parents("tr:first").find("[name=checkin]").html().getDate();if(getDate()>t)t=getDate();return t}
function editResvInGroupCheckOut(val,dom,isChanged){
	if(!isChanged) return;
	editResvInGroupCheckInCheckOut(dom,dom.parents("tr:first").find("[name=checkin]").html().getDate(),val.getDate());
}
function editResvInGroupCheckInCheckOut(dom,checkIn,checkOut){
	var resId = dom.parents("tr").attr("resid");
	var date = checkIn.toSystemFormat();
	var span = daysBetween(checkIn,checkOut);
	var link = "/reservationService?func=EditResvListCheckInCheckOut&resId="+resId+"&date="+date+"&span="+span;
	waitingDialog({});
	simpleserviceWithArgs(link,null,function(data,dom){
		var objArray = JSON.parse(data);
		var checkLogOut =  CheckSession(objArray);
		if(checkLogOut)
			return;
		var resv = dom.parents("tr:first");
		var resvTab = getObjectFromDataIndex(getCurrentTabData().GroupResvList,"resId",resv.attr("resId"));
		resvTab.ResData.date = objArray.date;
		resvTab.ResData.span = objArray.span;
		resvTab.ChargeList = objArray.Charge;
		showResvList(getCurrentTabData());
		closeWaitingDialog();
		//cerltimespan(savedSpan);
	},dom);
}

function changeGroupResvListOccupancy(dom)
{
	var roomtype = getObjectFromSharedData(SharedData.RoomType,dom.parents("tr:first").find("[roomtypeid]").attr("roomtypeid"));
	var occupancy = roomtype.MaxOccupancy;
	var min = (dom.attr("name") == "adult")? 1:0;
	fillSimpleNumberDropdown(dom,min,occupancy,changeGroupResvListOccupancyFinish,false,"width:40px;")
}
function changeGroupResvListOccupancyFinish(obj)
{
	var resId = obj.dom.parents("tr:first").attr("resid");
	
	waitingDialog({});
	
	var _data = {func:"editChildS",resvId:resId,child:obj.select.find(":selected").val()};
	if(obj.dom.attr("name") == "adult")
		_data = {func:"editAdultS",resvId:resId,adult:obj.select.find(":selected").val()};
	
	simpleserviceWithArgs("/reservationService",_data,function(data,obj){
		var objArray = JSON.parse(data);
		var checkLogOut =  CheckSession(objArray);
		if(checkLogOut)
			return;
		if($.trim(data) == 'true')
		{
			obj.dom.attr("refid",obj.select.val());
			obj.dom.text(obj.select.val());
			
			closeWaitingDialog();
			var Tabs = getCurrentTabData();
			if(Tabs != null)
			{
				var res = getObjectFromDataIndex(getCurrentTabData().GroupResvList,"resId",resId);
				res.ResData[obj.dom.attr("name")] = obj.select.val();
			}
		}
		else
			simpleDialog(saveFail_label,50,function(){cerltimespan(savedSpan);});
	},obj);
}

function ChangeTravel(name){
	var Tabs = getCurrentTabData();
	var type = Tabs.type;
	if(type!="Single"){
		if(name == "comeG")
		{
			$("[name=backG]").css("color","#999");
			$("[name=comeG]").css("color","#000");
			 $("#edit_res_resdetails_tarval").css("display","");
			$("#edit_res_resdetails_arrive").css("display","");
			$("[name=timeC]").css("display","");
			$("#edit_res_resdetails_addtask").css("display","");
			$("#edit_res_resdetails_tarval_Back").css("display","none");
			$("#edit_res_resdetails_arrive_Back").css("display","none");
			$("[name=timeB]").css("display","none");
			$("#edit_res_resdetails_addtask_Back").css("display","none");
		}
		else if(name == "backG")
		{
			$("[name=comeG]").css("color","#999");
			$("[name=backG]").css("color","#000");
			 $("#edit_res_resdetails_tarval").css("display","none");
				$("#edit_res_resdetails_arrive").css("display","none");
				$("[name=timeC]").css("display","none");
				$("#edit_res_resdetails_addtask").css("display","none");
				$("#edit_res_resdetails_tarval_Back").css("display","");
				$("#edit_res_resdetails_arrive_Back").css("display","");
				$("[name=timeB]").css("display","");
				$("#edit_res_resdetails_addtask_Back").css("display","");
		}
	}else{
			if(name == "comeG")
			{
				$("[name=backG]").css("color","#999");
				$("[name=comeG]").css("color","#000");
				
				 $("[id*=none_res_resdetails_tarval]").css("display","");
				$("[id*=none_res_resdetails_arrive]").css("display","");
				$("[name*=none_timeC]").css("display","");
				$("[id*=none_res_resdetails_addtask]").css("display","");
				
				$("[id*=none_res_resdetails_tarval_Back]").css("display","none");
				$("[id*=none_res_resdetails_arrive_Back]").css("display","none");
				$("[name=none_timeB]").css("display","none");
				$("[id*=none_res_resdetails_addtask_Back]").css("display","none");
			}
			else if(name == "backG")
			{
				$("[name=comeG]").css("color","#999");
				$("[name=backG]").css("color","#000");
				 $("[id*=none_res_resdetails_tarval]").css("display","none");
					$("[id*=none_res_resdetails_arrive]").css("display","none");
					$("[name*=none_timeC]").css("display","none");
					$("[id*=edit_none_res_resdetails_addtask]").css("display","none");
					
					$("[id*=none_res_resdetails_tarval_Back]").css("display","");
					$("[id*=none_res_resdetails_arrive_Back]").css("display","");
					$("[name=none_timeB]").show();
					$("#edit_none_res_resdetails_arrivetimeH_Back").show();
					$("#edit_none_res_resdetails_arrivetimeM_Back").show();
					$("[id*=edit_none_res_resdetails_addtask_Back]").css("display","");
			}
		}
}

function fillModeArrival() {
	var opts = SharedData.ArrivalMode.length;
	if($("[name=edit_res_resdetails_tarval] > option").length == 0){
		for ( var i = 0; i < opts; i++) {
		
			$("[name=edit_res_resdetails_tarval]").append( $("<option>").val(SharedData.ArrivalMode[i].id).html(SharedData.ArrivalMode[i].title));
			$("[name=edit_res_resdetails_tarval_Back]").append( $("<option>").val(SharedData.ArrivalMode[i].id).html(SharedData.ArrivalMode[i].title));
		}
	}
}

function SavedetailG()
{
	var dateofres = $('#edit_res_resdetails_checkin').val().getDate().toSystemFormat();
	var span = $('#edit_res_resdetails_restime').html();
	var extrabed = $('#edit_res_resdetails_extarbed').val();
	var reason = $('#edit_res_resdetails_objective').val();
	var source = $('#edit_res_resdetails_provenance').val();
	var dateCheckin =  $("#edit_res_resdetails_checkin").text();
	var link = "/reservationService?func=editDetailGroup&groupId=" + groupId+"&date="+dateofres+"&span="
	+span+"&extrabed="+extrabed+"&reason="+reason+"&source="+source;
	
	simpleservice(link,null,function(data){
		var objArray = JSON.parse(data);
		var checkLogOut =  CheckSession(objArray);
		if(checkLogOut){
			fillReservationDetailcantEdit();
			return;
		}
		var checkin = $("[id*=edit_res_resdetails_checkin]:visible").val();
		var checkout = $("[id*=edit_res_resdetails_checkout]:visible").val();
		var extrabed = $("[id*=edit_res_resdetails_extarbed]:visible").val();
		var reason = $("[id*=edit_res_resdetails_objective]:visible").val();
		var source = $("[id*=edit_res_resdetails_provenance]:visible").val();
		getCurrentTabData().ResData.date = checkin.getDate();
		getCurrentTabData().ResData.span = daysBetween(checkin.getDate(),checkout.getDate());
		getCurrentTabData().ResData.extrabed = extrabed;
		getCurrentTabData().ResData.Objective = reason;
		getCurrentTabData().ResData.sourcesString = source;
		fillReservationDetailcantEdit();
	});
}

function SavedetailS()
{
	//SaveInEntity("roomrate_amount");
	var dateofres = $('#edit_res_resdetails_checkin_S').val().getDate().toSystemFormat();
	var span = $('#edit_res_resdetails_restime_S').html();
	var extrabed = $('#edit_res_resdetails_extarbed_S').val();
	var reason = $('#edit_res_resdetails_objective_S').val();
	var source = $('#edit_res_resdetails_provenance_S').val();
	var link = "/reservationService?func=editDetailReservation&resId=" + res+"&date="+dateofres+"&span="
	+span+"&extrabed="+extrabed+"&reason="+reason+"&source="+source;
	waitingDialog({});
	simpleservice(link,null,function(data){
		var objArray = JSON.parse(data);
		var checkLogOut = CheckSession(objArray);
		if(checkLogOut){
			fillReservationDetailcantEdit();
			return;
		}
		if(objArray.PackageTable == null){
			var from = new Date(getCurrentTabData().ResData.dateTo);
			var to = $("[name*=edit_res_resdetails_checkout]:visible").text().getDate();
			splitReservationExtendDetailPage(getCurrentTabData().resId,$('table[name=subReservationList]'),from,to);
		}else{
			var checkin = $("[id*=edit_res_resdetails_checkin]:visible").val();
			var checkout = $("[id*=edit_res_resdetails_checkout]:visible").val();
			var extrabed = $("[id*=edit_res_resdetails_extarbed]:visible").val();
			var reason = $("[id*=edit_res_resdetails_objective]:visible").val();
			var source = $("[id*=edit_res_resdetails_provenance]:visible").val();
			
			getCurrentTabData().ResData.date = checkin.getDate();
			getCurrentTabData().ResData.span = daysBetween(checkin.getDate(),checkout.getDate());
			getCurrentTabData().ResData.extrabed = extrabed;
			getCurrentTabData().ResData.Objective = reason;
			getCurrentTabData().ResData.sourcesString = source;
			fillReservationDetailcantEdit();
			
			//cerltimespan(savedSpan);
			ResetSplitTable(objArray.SplitTable);
			ResetChargeList(objArray.ChargeList);
			ResetPackageTable(objArray.PackageTable);
		}
		closeWaitingDialog();
	});
}

function ResetSplitTable(splitData,Tabs)
{
	if(Tabs == null)
		Tabs = getCurrentTabData();
	if(Tabs == null)
		return;
	var df = splitData[0].date;
	var dt = splitData[0].dateTo;
	Tabs.SplitTable.Object = [];
	for(var i=0;i<splitData.length;i++)
	{
		var f = splitData[i].date;
		var t = splitData[i].dateTo;
		if(new Date(f) < new Date(df)) df = f;
		if(new Date(t) > new Date(dt)) dt = t;
		
		var roomId = splitData[i].roomString;
		var roomTypeId = splitData[i].roomTypeString;
		
		var room = getObjectFromSharedData(SharedData.Room,roomId);
		var roomType = getObjectFromSharedData(SharedData.RoomType,roomTypeId);
		
		Tabs.SplitTable.Object[i] = {};
		Tabs.SplitTable.Object[i].dateFrom = splitData[i].date;
		Tabs.SplitTable.Object[i].dateTo = splitData[i].dateTo;
		Tabs.SplitTable.Object[i].resId = splitData[i].id;
		Tabs.SplitTable.Object[i].roomId = roomId;
		Tabs.SplitTable.Object[i].roomName = room.roomName;
		Tabs.SplitTable.Object[i].roomTypeId = roomTypeId;
		Tabs.SplitTable.Object[i].roomTypeShortName = roomType.shortName;
	}
	Tabs.SplitTable.ResDate.date = df;
	Tabs.SplitTable.ResDate.dateTo = dt;
	Tabs.SplitTable.ResDate.id = splitData[0].parentId;
	Tabs.SplitTable.ResDate.span = daysBetween(new Date(df) < new Date(dt));
	if(getCurrentTabData() != null) renderReservationTableDetailPage(Tabs);
}

function ResetPackageTable(packageData,Tabs)
{
	if(Tabs == null)
		Tabs = getCurrentTabData();
	if(Tabs == null) return;
	for(var i=0;i<packageData.length;i++)
		delete packageData[i].packages;
	Tabs.PacByDate = packageData;
	if(getCurrentTabData() != null) fillPackageTable();
}

function ResetChargeList(chargeData,Tabs)
{
	if(Tabs == null)
		Tabs = getCurrentTabData();
	if(Tabs == null) return;
	Tabs.ChargeList = chargeData;
}

function LoadTravelDataSuccess(data,type) {
	if(data  == null)
		simpleDialog(saveFail_label);
	else
	{
		var datas =JSON.parse(data);
		var checkLogOut = CheckSession(datas);
		if(checkLogOut){
			fillTravelcantEdit();
			return;
		}
		var Tabs = getCurrentTabData();
		if(Tabs.type != "Group"){
			Tabs.SingleTravel=datas;
		}else{
			Tabs.GroupTravel = datas;
		}
		fillTravelcantEdit();
	}
}
	
function LoadTravelSuccess(data,type)
{ 
	var Tabs =getCurrentTabData();
	if(data != null){
	if(type != "Single"){
		$("[id=edit_res_resdetails_arrive]").val(data["arraive"]);
		var timeArraive = data["time"].split(" ");
		var objtimeArrive = timeArraive[3].split(":");
		var timeH = objtimeArrive[0];
		var timeM = objtimeArrive[1];
		if(data["showTime"]){
			$("[id=edit_res_resdetails_arrivetimeH]").val(timeH);
			$("[id=edit_res_resdetails_arrivetimeM]").val(timeM);
		}
		if(data["addTask"])
			$("[id*=edit_res_resdetails_addtask]").attr("checked",true);

		$("[id=edit_res_resdetails_arrive_Back]").val(data["arraiveBack"]);
		var timeBack = data["timeBack"].split(" ");
		var objtimeBack = timeBack[3].split(":");
		var timeBackH = objtimeBack[0];
		var timeBackM = objtimeBack[1];
		if(data["showTimeBack"]){
			$("[id=edit_res_resdetails_arrivetimeH_Back]").val(timeBackH);
			$("[id=edit_res_resdetails_arrivetimeM_Back]").val(timeBackM);
		}
		if(data["addTaskBack"])
			$("[id*=edit_res_resdetails_addtask_Back]").attr("checked",true);
	}else
	{
		$("[id=edit_none_res_resdetails_arrive]").val(data["arraive"]);
		var timeArraive = data["time"].split(" ");
		var objtimeArrive = timeArraive[3].split(":");
		var timeH = objtimeArrive[0];
		var timeM = objtimeArrive[1];
		if(data["showTime"]){
			$("[id*=none_res_resdetails_arrivetimeH]").val(timeH);
			$("[id*=none_res_resdetails_arrivetimeM]").val(timeM);
		}
		if(data["addTask"])
			$("[id*=none_res_resdetails_addtask]").attr("checked",true);
		
		$("[id=edit_none_res_resdetails_arrive_Back]").val(data["arraiveBack"]);
		var timeBack = data["timeBack"].split(" ");
		var objtimeBack = timeBack[3].split(":");
		var timeBackH = objtimeBack[0];
		var timeBackM = objtimeBack[1];
		if(data["showTimeBack"]){
			$("[id*=none_res_resdetails_arrivetimeH_Back]").val(timeBackH);
			$("[id*=none_res_resdetails_arrivetimeM_Back]").val(timeBackM);
		}
		if(data["addTaskBack"])
			$("[id*=none_res_resdetails_addtask_Back]").attr("checked",true);
	}
	}else
	{
		//Group
		$("[name*=res_resdetails_travelid]").attr("id","0");
		$("select[name*=res_resdetails_tarval]").val("0");  
		$("[name*=res_resdetails_arrive]").val("");
		$("[name*=res_resdetails_arrivetimeH]").val("");
		$("[name*=res_resdetails_arrivetimeM]").val("");
		$("select[name*=res_resdetails_tarval_Back]").val("0");
		$("[name*=res_resdetails_arrive_Back]").val("");
		$("[name*=res_resdetails_arrivetimeH_Back]").val("");
		$("[name*=res_resdetails_arrivetimeM_Back]").val("");	
		  //Single
		$("[id*=none_res_resdetails_arrive]").val("");
		$("[id*=none_res_resdetails_arrivetimeH]").val("");
		$("[id*=none_res_resdetails_arrivetimeM]").val("");
		$("[id*=none_res_resdetails_addtask]").attr("checked",false);
		$("select[id*=edit_none_res_resdetails_tarval_Back]").val("");
		$("[id*=none_res_resdetails_arrive_Back]").val("");
		$("[id*=none_res_resdetails_arrivetimeH_Back]").val("");
		$("[id*=none_res_resdetails_arrivetimeM_Back]").val("");
		$("[id*=none_res_resdetails_addtask_Back]").attr("checked",false);
	}

}

function saveCreditCard(){
	var obj = {};
	var Tabs = getCurrentTabData();
	obj.cardNo = $('[id*=edit_res_resdetails_creditcard]:visible').val();
	obj.cardType = $('[id*=edit_res_resdetails_creditcard2]:visible').val();
	obj.exMonth = $('[id*=edit_res_resdetails_creditcard_expire]:visible').val();
	obj.exYear = $('[id*=edit_res_resdetails_creditcard2_expire]:visible').val();
	obj.CVC = $('[id*=edit_res_resdetails_CVC]:visible').val();
	obj.cardId = (Tabs.type == "Group")? $('#edit_res_resdetails_creditcard_Id').val():$('#edit_res_resdetails_creditcard_Id_S').val();
	var tmpid = (Tabs.type == "Group")? "&groupId="+Tabs.resId : "&resId="+Tabs.resId;
	var link = "/CreditCardService?func=editCreditCard&CVC="+obj.CVC+"&cardType="+obj.cardType+"&NameOnCard="
		+""+"&cardNumber="+obj.cardNo+"&ExpiryDate="+obj.exMonth+"/"+obj.exYear+tmpid+"&creditCardId="+obj.cardId;
	waitingDialog({});
	simpleserviceWithArgs(link,null,saveCreditCardSuccess,obj);
}

function saveCreditCardSuccess(data,obj){
	closeWaitingDialog();
	var objArray = JSON.parse(data);
	if(objArray == null)
		simpleDialog(saveFail_label);
	else{
		var Tabs = getCurrentTabData();
		for(var i=0;i<Tabs.CreditCard.length;i++){
			if(Tabs.CreditCard[i].id == obj.cardId){
				Tabs.CreditCard[i].CardNumber = obj.cardNo;
				Tabs.CreditCard[i].CardType = obj.cardType;
				Tabs.CreditCard[i].ExpiryDate = obj.exMonth + "/" + obj.exYear;
				break;
			}
		}
	fillcreditCardcantEdit();
	}
}

function SavetoTasks()
{
	var Tabs = getCurrentTabData();
	var type = Tabs.type;
	var date = new Date();
	var ojb = {};
	if(type!="Single"){
		ojb.addTaskBack =$("[name=edit_res_resdetails_addtask_Back]").is(":checked");
		ojb.addTask =$("[name=edit_res_resdetails_addtask]").is(":checked");
	}else{
		ojb.addTaskBack =$("[name=edit_none_res_resdetails_addtask_Back]").is(":checked");
		ojb.addTask =$("[name=edit_none_res_resdetails_addtask]").is(":checked");
	}
	if(ojb.addTaskBack || ojb.addTask)
	{
		if(ojb.addTask)
		{
			if(type!="Single"){
				ojb.yravelby = $("[name=edit_res_resdetails_tarval]").attr("value");
				ojb.traveltext =$("#edit_res_resdetails_tarval").find($("[value="+ojb.yravelby+"]")).text();
				ojb.arrive =$("#edit_res_resdetails_arrive").attr("value");
				ojb.timeH =$("#edit_res_resdetails_arrivetimeH").attr("value");
				ojb.timeM =$("#edit_res_resdetails_arrivetimeM").attr("value");
				ojb.dateTime =$("[id*=edit_res_resdetails_checkin]:visible").text().getDate().toSystemFormat();
				if(ojb.timeH ==""&& ojb.timeM =="" || ojb.timeH == null&& ojb.timeM == null)
				{
					ojb.time =ojb.dateTime+" 00:00";
					ojb.showTime = false;
				}else{
					if(ojb.timeH =="" ||ojb.timeH == null)
						ojb.timeH ="00";
					if(ojb.timeM =="" ||ojb.timeM == null)
						ojb.timeM ="00";
					ojb.time =ojb.dateTime+" "+ojb.timeH +":"+ ojb.timeM;
					ojb.showTime =true;
				}
				var	link ="/taskService?func=AddTaskNoteGroup&detail="+ojb.arrive+"&due="+ojb.time+'&isStar=false&roomName=&status=Normal&taskTitle='+ojb.traveltext+'&group_id='+ Tabs.resId;
				simpleserviceWithArgs(link,null,AddtaskNoteSuccess,Tabs);
			}else{
				ojb.yravelby = $("#edit_none_res_resdetails_tarval").attr("value");
				ojb.traveltext =$("#edit_none_res_resdetails_tarval").find($("[value="+ojb.yravelby+"]")).text();
				ojb.arrive =$("#edit_none_res_resdetails_arrive").attr("value");
				ojb.timeH =$("#edit_none_res_resdetails_arrivetimeH").attr("value");
				ojb.timeM =$("#edit_none_res_resdetails_arrivetimeM").attr("value");
				ojb.dateTime =$("[id*=edit_res_resdetails_checkin]:visible").text().getDate().toSystemFormat();
				if(ojb.timeH ==""&&ojb.timeM =="" || ojb.timeH == null&&ojb.timeM == null)
				{
					ojb.time =ojb.dateTime+" 00:00";
					ojb.showTime = false;
				}else{
					if(ojb.timeH =="" ||ojb.timeH == null)
						ojb.timeH ="00";
					if(ojb.timeM =="" ||ojb.timeM == null)
						ojb.timeM ="00";
					
					ojb.time =ojb.dateTime+" "+ojb.timeH +":"+ ojb.timeM;
					ojb.showTime = true;
				}
				var	link ="/taskService?func=AddTaskNote&detail="+ojb.arrive+"&due="+ojb.time+'&isStar=false&roomName=&status=Normal&taskTitle='+ojb.traveltext+'&res_id='+  Tabs.resId;
				simpleserviceWithArgs(link,null,AddtaskNoteSuccess,Tabs);
			}
		}
		if(ojb.addTaskBack == true)
		{
			if(type!="Single"){
				ojb.yravelbyBack = $("[name=edit_res_resdetails_tarval_Back]").attr("value");
				ojb.traveltextBack =$("#edit_res_resdetails_tarval_Back").find($("[value="+ojb.yravelbyBack+"]")).text();
				ojb.arriveBack =$("#edit_res_resdetails_arrive_Back").attr("value");
				ojb.timeHBack =$("#edit_res_resdetails_arrivetimeH_Back").attr("value");
				ojb.timeMBack =$("#edit_res_resdetails_arrivetimeM_Back").attr("value");
				
				ojb.dateTimeBack = $("[id*=edit_res_resdetails_checkout]:visible").text().getDate().toSystemFormat();
				if(ojb.timeHBack ==""&& ojb.timeMBack =="" || ojb.timeHBack == null&& ojb.timeMBack == null)
				{
					ojb.timeBack =ojb.dateTimeBack+" 00:00";
					ojb.showTimeBack = false;
				}
				else
				{
					if(ojb.timeHBack =="" ||ojb.timeHBack == null)
						ojb.timeHBack ="00";
					if(ojb.timeMBack =="" ||ojb.timeMBack == null)
						ojb.timeMBack ="00";
					ojb.timeBack =ojb.dateTimeBack+" "+ojb.timeHBack+":"+ojb.timeMBack;
					ojb.showTimeBack = false;
				}
				var	link ="/taskService?func=AddTaskNoteGroup&detail="+ojb.arriveBack+"&due="+ojb.timeBack+'&isStar=false&roomName=&status=Normal&taskTitle='+ojb.traveltextBack+'&group_id='+Tabs.resId;
				simpleserviceWithArgs(link,null,AddtaskNoteSuccess,Tabs);
				
			}else{
				
				ojb.yravelbyBack = $("#edit_none_res_resdetails_tarval_Back").attr("value");
				ojb.traveltextBack =$("#edit_none_res_resdetails_tarval_Back").find($("[value="+ojb.yravelbyBack+"]")).text();
				ojb.arriveBack =$("#edit_none_res_resdetails_arrive_Back").attr("value");
				ojb.timeHBack =$("#edit_none_res_resdetails_arrivetimeH_Back").attr("value");
				ojb.timeMBack =$("#edit_none_res_resdetails_arrivetimeM_Back").attr("value");
				ojb.dateTimeBack = $("[id*=edit_res_resdetails_checkout]:visible").text().getDate().toSystemFormat();
				if(ojb.timeHBack ==""&&ojb.timeMBack =="" || ojb.timeHBack == null&&ojb.timeMBack == null)
				{
					ojb.timeBack =ojb.dateTimeBack+" 00:00";
					ojb.showTimeBack = false;
				}
				else
				{
					if(ojb.timeHBack =="" ||ojb.timeHBack == null)
						ojb.timeHBack ="00";
					if(ojb.timeMBack =="" ||ojb.timeMBack == null)
						ojb.timeMBack ="00";
					
				    ojb.timeBack =ojb.dateTimeBack+" "+ojb.timeHBack +":"+ ojb.timeMBack;
				    ojb.showTimeBack = true;
				}
				var	link ="/taskService?func=AddTaskNote&detail="+ ojb.arriveBack+"&due="+ ojb.timeBack+'&isStar=false&roomName=&status=Normal&taskTitle='+ ojb.traveltextBack+'&res_id='+Tabs.resId;
				simpleserviceWithArgs(link,null,AddtaskNoteSuccess,Tabs);
			}
		}
	}
}

function SaveTravel(){
	var ojb ={};
	var Tabs =getCurrentTabData();
	var Type =Tabs.type;
	if(Type != "Single"){
		ojb.yravelby = $("[name=edit_res_resdetails_tarval]").attr("value");
		ojb.arrive =$("#edit_res_resdetails_arrive").attr("value");
		ojb.timeH =$("[name=edit_res_resdetails_arrivetimeH]").attr("value");
		ojb.timeM =$("[name=edit_res_resdetails_arrivetimeM]").attr("value");
		
		ojb.dateTime =$("[id*=edit_res_resdetails_checkin]:visible").text().getDate().toSystemFormat();
		if(ojb.timeH ==""&& ojb.timeM =="" || ojb.timeH == null&& ojb.timeM == null)
		{
			ojb.time=ojb.dateTime+" 00:00";
			ojb.showTime = false;
		}
		else
		{
			if(ojb.timeH =="" ||ojb.timeH == null)
				ojb.timeH ="00";
			if(ojb.timeM =="" ||ojb.timeM == null)
				ojb.timeM ="00";
			ojb.time =ojb.dateTime+" "+ojb.timeH +":"+ ojb.timeM;
			ojb.showTime =true;
		}	
		ojb.addTask =$("#edit_res_resdetails_addtask").is(":checked");
		ojb.yravelbyBack = $("[name=edit_res_resdetails_tarval_Back]").attr("value");
		ojb.arriveBack =$("[name=edit_res_resdetails_arrive_Back]").attr("value");
		ojb.timeHBack =$("[name=edit_res_resdetails_arrivetimeH_Back]").attr("value");
		ojb.timeMBack =$("[name=edit_res_resdetails_arrivetimeM_Back]").attr("value");
		
		ojb.dateTimeBack = $("[id*=edit_res_resdetails_checkout]:visible").text().getDate().toSystemFormat();
		if(ojb.timeHBack ==""&& ojb.timeMBack =="" || ojb.timeHBack == null&& ojb.timeMBack == null)
		{
			ojb.timeBack =ojb.dateTimeBack+" 00:00";
			ojb.showTimeBack = false;
		}
		else
		{
			if(ojb.timeHBack =="" ||ojb.timeHBack == null)
				ojb.timeHBack ="00";
			if(ojb.timeMBack =="" ||ojb.timeMBack == null)
				ojb.timeMBack ="00";
			ojb.timeBack =ojb.dateTimeBack+" "+ojb.timeHBack+":"+ojb.timeMBack;
			ojb.showTimeBack = false;
		}
		ojb.addTaskBack =$("[name=edit_res_resdetails_addtask_Back]").is(":checked");
		ojb.travelId =$("[name=edit_res_resdetails_travelid]").attr("id");
	}
	else
	{
		ojb.yravelby = $("#edit_none_res_resdetails_tarval").attr("value");
		ojb.arrive =$("#edit_none_res_resdetails_arrive").attr("value");
		ojb.timeH =$("#edit_none_res_resdetails_arrivetimeH").attr("value");
		ojb.timeM =$("#edit_none_res_resdetails_arrivetimeM").attr("value");
		ojb.dateTime =new Date(Tabs.ResData.date).toSystemFormat();
		if(ojb.timeH ==""&&ojb.timeM =="" || ojb.timeH == null&&ojb.timeM == null)
		{
			ojb.time =ojb.dateTime+" 00:00";
			ojb.showTime = false;
		}else{
			if(ojb.timeH =="" ||ojb.timeH == null)
				ojb.timeH ="00";
			if(ojb.timeM =="" ||ojb.timeM == null)
				ojb.timeM ="00";
			ojb.time =ojb.dateTime+" "+ojb.timeH +":"+ ojb.timeM;
			ojb.showTime = true;
		}
		ojb.addTask =$("#edit_none_res_resdetails_addtask").is(":checked");
		ojb.yravelbyBack = $("#edit_none_res_resdetails_tarval_Back").attr("value");
		ojb.arriveBack =$("#edit_none_res_resdetails_arrive_Back").attr("value");
		ojb.timeHBack =$("#edit_none_res_resdetails_arrivetimeH_Back").attr("value");
		ojb.timeMBack =$("#edit_none_res_resdetails_arrivetimeM_Back").attr("value");
		ojb.dateTimeBack = new Date(Tabs.ResData.dateTo).toSystemFormat();
		if(ojb.timeHBack ==""&&ojb.timeMBack =="" || ojb.timeHBack == null&&ojb.timeMBack == null)
		{
			ojb.timeBack =ojb.dateTimeBack+" 00:00";
			ojb.showTimeBack = false;
		}
		else
		{
			if(ojb.timeHBack =="" ||ojb.timeHBack == null)
				ojb.timeHBack ="00";
			if(ojb.timeMBack =="" ||ojb.timeMBack == null)
				ojb.timeMBack ="00";
			
			ojb.timeBack =ojb.dateTimeBack+" "+ojb.timeHBack +":"+ ojb.timeMBack;
			ojb.showTimeBack = true;
		}
		ojb.addTaskBack =$("#edit_none_res_resdetails_addtask_Back").is(":checked");
		ojb.travelId =Tabs.ResData.travelString;
	}
	if(ojb.travelId == null || ojb.travelId == "" || ojb.travelId =="0"){
		var tmpid = (Tabs.type != "Single")?"&groupId="+Tabs.resId+"&resId=0" : "&groupId=0&resId="+Tabs.resId;
		var link = "/TravelService?func=addtravel&tarvelby="+ojb.yravelby+"&arrive="+ojb.arrive+"&time="+ojb.time+"&addTask="+ojb.addTask+"&tarvelbyBack="+ojb.yravelbyBack+"&arriveBack="+ojb.arriveBack+"&timeBack="+ojb.timeBack+"&addTaskBack="+ojb.addTaskBack+tmpid+"&showTime="+ ojb.showTime+"&showTimeBack="+ ojb.showTimeBack;
		simpleserviceWithArgs(link,null,LoadTravelDataSuccess,Tabs.type);
	}
	else{
		var tmpid = (Tabs.type != "Single")?"&groupId="+Tabs.resId+"&resId=0" : "&groupId=0&resId="+Tabs.resId;
		var	link="/TravelService?func=edittravel&id="+ojb.travelId+"&tarvelby="+ojb.yravelby+"&arrive="+ojb.arrive+"&time="+ojb.time+"&addTask="+ojb.addTask+"&tarvelbyBack="+ojb.yravelbyBack+"&arriveBack="+ojb.arriveBack+"&timeBack="+ojb.timeBack+"&addTaskBack="+ojb.addTaskBack+tmpid+"&showTime="+ ojb.showTime+"&showTimeBack="+ ojb.showTimeBack;
		simpleserviceWithArgs(link,null,LoadTravelDataSuccess,Tabs.type);
	}
	$('[name=saveTravel]').css("display","none");
}

function AddtaskNoteSuccess(data,Tabs)
{
	var objArray = JSON.parse(data);
	var checkLogOut = CheckSession(objArray);
	if(checkLogOut){
		fillTravelcantEdit();
		return;
	}
	if(objArray == null)
		simpleDialog(saveFail_label);
	else
	{
		if(Tabs.type!="Single")
		{
			$("#edit_res_resdetails_addtask").attr('checked', false);
			$("[name=edit_res_resdetails_addtask_Back]").attr('checked', false);
		}else
		{
			$("#edit_none_res_resdetails_addtask").attr('checked', false);
			$("[name=edit_none_res_resdetails_addtask_Back]").attr('checked', false);
		}
		$("[id*=addtasks][id*=_note_id]:visible").val("");
		var Tabs = getCurrentTabData();
		if(Tabs.Task == null) Tabs.Task = [];
		Tabs.Task.push(objArray);
		selectDisplayTask(getCurrentTabData());
	}
}

function fillSourceBuss(){
	var selected = $("[id*=edit_res_resdetails_provenance]:visible");
	selected.find("option").remove();
	selected.append("<option value=''>"+simpleLabel_Select+"</option>");
	for(var i=0;i<SharedData.SourcesBusiness.length;i++)
		selected.append("<option value='"+SharedData.SourcesBusiness[i].id+"'>"+SharedData.SourcesBusiness[i].title+"</option>");
	selected.val(0);
}

function fillCreditCardType(){
	var ccType = SharedData.CreditCardType;
	var selected = $("[name=addcreditCard_type]:visible,[name*=edit_res_resdetails_creditcard2]:visible");
	selected.find("option").remove();
	selected.append("<option value=''>"+addcreditCardtype+"</option>");
	for(var i=0;i<ccType.length;i++)
		selected.append("<option value='"+ccType[i].id+"'>"+ccType[i].CardTypeName+"</option>");
	selected.val(0);
}
function AssignRoom(){
	if(res != 0){
		var assign = $('#edit_none_groups_checkroom').is(':checked');
		var roomId = getCurrentTabData().ResData.roomString;
		var roomNameChose = $('#edit_none_groups_cbroom :selected').html();
		var link = "/reservationService?func=assignRoom&resId="+res+"&isAssign="+assign+"&roomId="+roomId;
		simpleservice(link,null,function(data){
			var objArray = JSON.parse(data);
			var checkLogOut = CheckSession(objArray);
			if(checkLogOut)
				return;
			$('#edit_none_groups_checkroom').attr("disabled",true);
			(roomNameChose !=null)?$("#edit_none_groups_cbroom").replaceWith("<span id=\"edit_none_groups_cbroom\" >"+roomNameChose+"</span>"):"";
		});
	}
}

//To close dialog call onclick="destroyLocalDialog(this,null)" || onclick="destroyLocalDialog(this,callback)"
function destroyLocalDialog(el,callback)
{
	if(callback != null)
		callback(el);
	$(el).parents("div.ui-dialog-content").dialog("destroy");
}

function ShowCalendar()
{
	$("[name*=roomrate_date_endDate]").click(function (e) {
		var minDate = $(this).parent().find("[name=roomrate_date_StartDate]").text().getDate().addDate(1);
		var maxDate = $("[id*=edit_res_resdetails_checkout]:visible").val().getDate();
		var Dom =$(e.srcElement).parents("tr:first");
		var checkoutDate =Dom.find($("[name=roomrate_date_endDate]:visible")).text().getDate();
		SelectDateTimePicker(this,"top",minDate,maxDate,function(val,dom,isChanged){
			if(!isChanged) return;
			var obj ={};
			obj.pacId =Dom.children("td:first").find("div").attr("refid");
			obj.pacdateId =Dom.attr("refid");
			obj.checkinDate = Dom.find($("[name=roomrate_date_StartDate]:visible")).text().getDate();
			obj.checkoutDate = checkoutDate;
			obj.NewDateTo = Dom.find($("[name=roomrate_date_endDate]:visible")).text().getDate();
			obj.span = daysBetween(obj.checkinDate,obj.NewDateTo);
			Dom.find($("div[name*=roomrate_night]:visible")).text(obj.span);
			
			EditPackageDate(obj);
		},-170,0);
	});
}

function EditPackageDate(obj)
{
	var Tabs = getCurrentTabData();
	var resId = Tabs.resId;
	var span=daysBetween(obj.NewDateTo,obj.checkoutDate);
	var inDate =obj.checkinDate.toSystemFormat();
	var outDate =obj.checkoutDate.toSystemFormat();
	var newDate =obj.NewDateTo.toSystemFormat();
	if(span != 0)
	{
		var link = "/packageService?doClass=editPackageByDate&packageId="+obj.pacId+"&pacByDateId="+obj.pacdateId
			+"&dateForm="+inDate+"&dateTo="+outDate+"&resId="+resId+"&NewTodate="+newDate;
		waitingDialog({});
		simpleserviceWithArgs(link,null,ChargePackageSuccess,obj);
	}
}

// Date value and tranform
function getcheckInTime()
{
	var checkInT = new Date(SharedData.General.checkInTime);
	return (60000*(checkInT.getHours()*60))+(60000*checkInT.getMinutes());
}
function getcheckOutTime()
{
	var checkOutT = new Date(SharedData.General.checkOutTime);
	return (60000*(checkOutT.getHours()*60))+(60000*checkOutT.getMinutes());
}

function getnightAuditTime()
{
	var nightAuditT = new Date(SharedData.General.nightAuditTime);
	return (60000*(nightAuditT.getHours()*60))+(60000*nightAuditT.getMinutes());
}
//return date and time checkin day at night audit time 
function getEarlyCheckOut()
{
	var night =getCurrentTabData().ResData.span;
	var checkIn = getCurrentTabData().ResData.date;
	return new Date(new Date(checkIn).addDate(night).getTime()+getnightAuditTime());
}

function getEarlyCheckin()
{
	var checkIn = getCurrentTabData().ResData.date;
	return getServerDateTime().getTime() > new Date(checkIn).getTime()+getnightAuditTime()&&getServerDateTime().getTime()<new Date(checkIn).getTime()+getcheckInTime();
}

function sortDateCancelPolicy()
{
	var cancelPolicyArray = [];
	var cancelPolicy=SharedData.CancellationPolicy;
	if(getCurrentTabData().ResData==null)
		return
	  var checkInTime = new Date(getCurrentTabData().ResData.date).getTime()+getcheckInTime();
	  var nightAuditTime = new Date(getCurrentTabData().ResData.date).getTime()+getnightAuditTime();
		
	if(cancelPolicy == null)
		return;
	var hours = 0;
	for(var i = 0;i<cancelPolicy.length;i++)
	{
		if(cancelPolicy[i].Days!=0)
			hours = cancelPolicy[i].Days*24;
		else
			hours =cancelPolicy[i].Hours
		cancelPolicyArray.push(new Date(checkInTime - 60000*(hours * 60)));
	}	
	cancelPolicyArray.sort(function(a,b){ return new Date(a.date)-new Date(b.date); });

	return cancelPolicyArray;
}
function ShowSinglePaymentPage()
{
	if($("div[forload=editreserved] #payment-dialog").size() == 0){
		var div = $("<div>");
		$("div[forload=editreserved]").append(div);
		div.load("/components/Payment/Payment.jsp",function(){
			ShowSiinglePaymentPageCheckedElement()
		});
	}
	else ShowSiinglePaymentPageCheckedElement()
}
function ShowSiinglePaymentPageCheckedElement(){
	var Tabs = getCurrentTabData();
	if(Tabs.Owner == null){
		(Tabs.type != "Group")?simpleDialog("fill owner name."):simpleDialog("fill group owner name.");
		return;
	}if(Tabs.Owner.firstName == "")
	{
		(Tabs.type != "Group")?simpleDialog("fill owner name."):simpleDialog("fill group owner name.");
		return;
	}
	if(Tabs.resId ==0||Tabs.ResData.reservationStatusName =="Temp Rooms"){btnReservation($('<input type="button" setButton="payMent">')[0])}
	var ScritpArray=[];
	ScritpArray.push("/js/components/Payment/Charges.js");
	ScritpArray.push("/js/components/Payment/Refund.js");
	ScritpArray.push("/js/components/Payment/MenageFolio.js");
	ScritpArray.push("/js/components/Payment/SinglePaymentGroup.js");
	ScritpArray.push("/js/components/Payment/Payment.js");
	if(Tabs!=undefined){
		if(Tabs.type == "Single")
			CheckAllScript(ScritpArray,function(){SinglePage()},null);
		if(Tabs.type=="Group")
			CheckAllScript(ScritpArray,function(){ShowPaymentPage()},null);
	}
}
function SelectDateTimePicker(el,position,min,max,callback,xOffset,yOffset,enableTime)
{
	var top_value = (position=="top")? $(el).offset().top-225 : $(el).offset().top + $(el).height();
	var left_value = ($(el).offset().left-100);
	top_value = (yOffset==null)? top_value : top_value+yOffset;
	left_value = (xOffset==null)? left_value : left_value+xOffset;
	$(".datepicker").datepicker("option", "dateFormat", SharedData.General.dateFormat.dateTimeFormat);
	$(".datepicker").datepicker("option", "minDate", min);
	$(".datepicker").datepicker("option", "maxDate", max);
	fillQuickDate();
	$(".pageheader").css("display", "");
    $('.pageheader').offset({ top: top_value, left: left_value });
	$('.pageheader').get(0).change = $(el);
	$('.pageheader').get(0).callback = callback;
	var maxZ = MaxDivZIndex();
	$('.pageheader').css("z-index",maxZ+1);
	$('.datepickerShow').val(($(el).html()=="")? $(el).val(): $(el).html());
	if(enableTime==null || enableTime==false)
		$("[name=textfield2]:visible").css("display","none");
	else{
		$("[name=textfield2]:visible").css("display","");
		var tmpval = ($(el).html()=="")? $(el).val().split("&nbsp; &nbsp;"): $(el).html().split("&nbsp; &nbsp;");
		$('.datepickerShow').val(tmpval[0]);
		$("[name=textfield2]").val((tmpval[1]==null)?"00:00":tmpval[1]);
		$("[name=textfield2]").timepicker();
	}
}

function CalBalancetoShow()
{
	var roomsPrice=0;
	var otherCharge=0;
	var otherdiscount=0;
	var roomdiscount=0;
	var roomsTax=0;
	var otherTax=0;
	var roomsPriceforAcc=0;
	var roomdiscountforAcc=0;
	var roomsTaxforAcc=0;
	var Tabs = getCurrentTabData();
	var chargeAry =[];
	if(Tabs.type =="Single"){
		var otherchargeAry =Tabs.OtherChargeList;
		for(var i= 0;i<Tabs.ChargeList.length;i++)
			chargeAry.push(Tabs.ChargeList[i]);
		if(otherchargeAry!= null)
			for(var i= 0;i<otherchargeAry.length;i++)
				chargeAry.push(otherchargeAry[i]);
	}
	var cResArray = [];
	$.each(chargeAry, function(i,el){ 
		var idCheck = (cResArray.length!=0)?cResArray[i-1]['id']:cResArray;
		if(el['id']!=idCheck){ cResArray.push(el);}
		});
	for(var i=0;i<cResArray.length;i++)
	{
		if(cResArray[i].isRoomCharge == true&&cResArray[i].isRefund != true)
		{
			roomsPrice +=parseFloat(cResArray[i].chargeAmount);
			roomsTax +=parseFloat(cResArray[i].tax);
			roomdiscount+=parseFloat(cResArray[i].discount);
			if(!cResArray[i].isTemp){
				roomsPriceforAcc +=parseFloat(cResArray[i].chargeAmount);
				 roomsTaxforAcc+=parseFloat(cResArray[i].tax);
				 roomdiscountforAcc+=parseFloat(cResArray[i].discount);
			}
		}
		if(cResArray[i].isRoomCharge != true &&cResArray[i].isRefund != true)
		{
			otherCharge +=parseFloat(cResArray[i].chargeAmount);
			otherTax +=parseFloat(cResArray[i].tax);
			otherdiscount+=parseFloat(cResArray[i].discount);
		}
		
	}
	//payment
	var paymentAry = Tabs.PaymentList;
	var payprice = 0;
	if(paymentAry != null)
	for(var i=0;i<paymentAry.length;i++)
		payprice +=parseFloat(paymentAry[i].amount)
	var totalprices = parseFloat(otherCharge)+parseFloat(roomsPrice);
	
	if(!SharedData.incloudetax){
		totalprices -=(parseFloat(roomsTax)+parseFloat(otherTax));
		roomsPrice -=roomsTax;
		otherCharge -=otherTax;
	}
	Tabs.calBalance={
			roomsPrice:roomsPrice,
			roomdiscount:roomdiscount,
			roomsTax:roomsTax,
			otherCharge:otherCharge,
			otherdiscount:otherdiscount,
			otherTax:otherTax,
			TotalBalance:totalprices,
			payprice:payprice,
			chargePriceAcc:totalprices-roomsPrice,
			roomdiscountAcc:(roomdiscount+otherdiscount)-roomdiscountforAcc,
			roomsTaxAcc:(roomsTax+otherTax)-roomsTaxforAcc
			};
}

function fillBalanceSingleDetail(){
	var Tabs = getCurrentTabData();
	$('[id*=roomPrice]:visible').html(toCurrencyString(Tabs.calBalance.roomsPrice,false));
	$('[id*=otherPrice]:visible').html(toCurrencyString(Tabs.calBalance.otherCharge,false));
	$('[id*=taxCost]:visible').html(toCurrencyString(Tabs.calBalance.roomsTax+Tabs.calBalance.otherTax,false));
	$('[id*=totalCost]:visible').html(toCurrencyString(Tabs.calBalance.TotalBalance,false));
	$('[id*=payprice]:visible').html(toCurrencyString(Tabs.calBalance.payprice,false));
	$('#rest:visible').html(toCurrencyString((Tabs.calBalance.TotalBalance+(parseFloat(Tabs.calBalance.roomsTax)+parseFloat(Tabs.calBalance.otherTax)))-Tabs.calBalance.payprice,false));
}

function GroupCalBalancetoShow()
{
	var roomsPrice=0;
	var otherCharge=0;
	var roomsTax=0;
	var otherTax=0;
	var discount=0;
	var roomdiscount=0;
	var otherDiscount=0;
	var refund =0;
	var otherrefund=0;
	var roomsPriceforAcc=0;
	var roomdiscountforAcc=0;
	var roomsTaxforAcc=0;
	var Tabs = getCurrentTabData();
	var chargeAry =[];
	if(Tabs.type =="Group")
	{ 
		if(Tabs.ChargeList != null){
			for(var i= 0;i<Tabs.ChargeList.length;i++)
				chargeAry.push(Tabs.ChargeList[i]);
		}
		if(Tabs.GroupResvList != null){
			for(var i =0;i<Tabs.GroupResvList.length;i++)
			{
				for(var n= 0; n<Tabs.GroupResvList[i].ChargeList.length;n++)
					chargeAry.push(Tabs.GroupResvList[i].ChargeList[n]);
			}
		}
	}
	var cResArray = [];
	$.each(chargeAry, function(i,el){ 
		var idCheck = (cResArray.length!=0)?cResArray[i-1]['id']:cResArray;
		if(el['id']!=idCheck){ cResArray.push(el);}
		});
	for(var i=0;i<cResArray.length;i++)
	{
		if(cResArray[i].isRoomCharge == true &&cResArray[i].isRefund != true)
		{
			roomsPrice +=parseFloat(cResArray[i].chargeAmount);
			roomsTax +=parseFloat(cResArray[i].tax);
			discount +=parseFloat(cResArray[i].discount);
			if(!cResArray[i].isTemp){
				roomsPriceforAcc +=parseFloat(cResArray[i].chargeAmount);
				 roomsTaxforAcc+=parseFloat(cResArray[i].tax);
				 roomdiscountforAcc+=parseFloat(cResArray[i].discount);
			}
		}
		if(cResArray[i].isRoomCharge != true &&cResArray[i].isRefund != true)
		{
			otherCharge +=parseFloat(cResArray[i].chargeAmount);
			otherTax +=parseFloat(cResArray[i].tax);
			otherDiscount+=parseFloat(cResArray[i].discount);
		}
		if(cResArray[i].isRefund == true)
		{
			refund +=parseFloat(cResArray[i].chargeAmount);
			otherrefund+=parseFloat(cResArray[i].chargeAmount);
		}
	
	}
	if(Tabs.type=="Group"&& Tabs.GroupPaymentList != null)var paymentAry = Tabs.GroupPaymentList;
	var payprice = 0;
	if(paymentAry != null)
	for(var i=0;i<paymentAry.length;i++)
		payprice +=parseFloat(paymentAry[i].amount)
	
	var totalprice = parseFloat(otherCharge)+parseFloat(roomsPrice)-(parseFloat(otherDiscount)+parseFloat(discount));

	if(!SharedData.incloudetax){
		totalprice -=(parseFloat(roomsTax)+parseFloat(otherTax));
		roomsPrice -=roomsTax;
		otherCharge -=otherTax;
	}
	Tabs.calBalance={
			roomsPrice:roomsPrice,
			roomdiscount:roomdiscount,
			roomsTax:roomsTax,
			otherCharge:otherCharge,
			otherdiscount:otherDiscount,
			otherTax:otherTax,
			TotalBalance:totalprice,
			payprice:payprice,
			chargePriceAcc:totalprice-roomsPrice,
			roomdiscountAcc:(roomdiscount+otherDiscount)-roomdiscountforAcc,
			roomsTaxAcc:(roomsTax+otherTax)-roomsTaxforAcc
			};
	//Group
	$('#edit_pay:visible').html(toCurrencyString(payprice,false));
	$('#edit_discount:visible').html(toCurrencyString((otherDiscount+discount),false));
	$('#edit_tax:visible').html(toCurrencyString((roomsTax+otherTax),false));
	$('#edit_otherCharge:visible').html(toCurrencyString(otherCharge,false));
	$('#edit_total:visible').html(toCurrencyString(totalprice,false));
	$('#edit_roomDiscount:visible').html(toCurrencyString(discount,false));
	$('#edit_roomCharge:visible').html(toCurrencyString(roomsPrice,false));
	$('#edit_balance:visible').html(toCurrencyString((totalprice-payprice),false))
	$('#editreserved_refund_amount:visible').html(toCurrencyString(refund+otherrefund,false));
}

function CreateChargeforEmptyRoom(charegAmt,Tabs)
{ 
	Tabs.ChargeList=[];
	var objprice =calTax(parseFloat(charegAmt),0,SharedData.General.incloudetax);
	var Object={
	FolioId: 0,
	Qty: 0,
	chargeAmount: objprice.costIncludeTax,
	chargeDate:$.datepicker.parseDate("yy-mm-dd",$(dateStart).attr('dateform')).toString(),
	description: "Room Rate",
	discount: 0,
	hotelId: 1,
	id: 0,
	isLock: false,
	isRefund: false,
	isRoomCharge: true,
	isTemp: true,
	reasondetailId: 0,
	subFolio: "0",
	tax: objprice.tax
	};
	Tabs.ChargeList.push(Object)
	CreatePackageForEmptyRoom(Tabs);
}

function CreatePaymentForEmptyRoom(Tabs)
{
	Tabs.PaymentList=[];
	var Object={
	amount: $('#pledge').val(),
	avaliable: true,
	ccNo: "",
	ccNo2: "0",
	description: "",
	folioId: 0,
	hotelId: 1,
	parentPaymentString: "",
	payDate: $.datepicker.parseDate("yy-mm-dd",$(dateStart).attr('dateform')).toString(),
	payMode: "Cash",
	payTypeString: "4106",
	resIdString: ""
	}
	Tabs.PaymentList.push(Object);
}

function CreatePackageForEmptyRoom(Tabs){
	Tabs.PacByDate=[];
	var Object ={
	dateFrom: $.datepicker.parseDate("yy-mm-dd",$(dateStart).attr('dateform')).toString(),
	dateTo: $.datepicker.parseDate("yy-mm-dd",$('#dateEnd').attr('dateend')).toString(),
	id: 0,
	packageString: $('[name=SeasonalRate]').find('option:selected').val()
	}
	Tabs.PacByDate.push(Object);
}

function getValOrText(dom){
	if( dom.val() == null){
		return dom.text();
	}else{
		return dom.val();
	}
}

function SaveNoteSingle(e) {
	var valueText =$("#edi_res_groups_note_S").attr("value");
	var Tabs =getCurrentTabData();
	if (e.keyCode == 13 && e.shiftKey) {
		$(this).val(function(i,val){return val + "\n";})
	}
	var valueTextArea = document.getElementById("edi_res_groups_note_S").value;
	var link = "/reservationService?func=editNote&note=" + valueTextArea+"&groupId=0&resId="+Tabs.resId;
	simpleserviceWithArgs(link,null,EditNoteSuccess);
}

function SaveNoteGroup(e) {
	var valueText =$("#edi_res_groups_note").attr("value");
	var Tabs =getCurrentTabData();
	if (e.keyCode == 13 && e.shiftKey) {
		$(this).val(function(i,val){return val + "\n";})
	}
	var valueTextArea = document.getElementById("edi_res_groups_note").value;
	var link = "/reservationService?func=editNote&note=" + valueTextArea+"&groupId="+Tabs.resId+"&resId=0";
	simpleserviceWithArgs(link,null,EditNoteSuccess);
}

function EditNoteSuccess(data,id)
{
	var datas = JSON.parse(data);
	if(datas.result==false){
		var buttons = [{ title:"OK" , callback: function(thisdialog,args){window.location.assign("logout.jsp");}}];
   		customDialog(Warning,ForceLogout,null,buttons,null);
	}else{
		if(datas  == null)
			simpleDialog(saveFail_label);
		else
		{
			var checkLogOut = CheckSession(objArray);
			if(checkLogOut)
				return;
			var Tabs =getCurrentTabData();
			var resId =Tabs.resId;
			
			if(Tabs.type == "Single")
				var data = { func : "getReservation", resId: resId };
			else if(Tabs.type == "Group")
				var data = { func : "loadGroup", groupId: resId };

			var url = "/reservationService";
			simpleservice(url,data,function(data){
					var objArray = JSON.parse(data);
					var Tabs = getTabsData(objArray.id);
					Tabs.ResData = objArray;
			});
			
			$("#"+id).replaceWith("<textarea id =\""+id+"\" style=\"width:580px; background-color:#EAEAEA; border-color:#FFF;\" rows=\"2\" onkeypress=\"SavetoEntity(id,event)\">"+datas+"</textarea>");
			return false;
		}
	}
}